0
0
Spring Bootframework~30 mins

@Scope for bean scope in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
@Scope for bean scope in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that manages user sessions. You want to control how Spring creates and manages your beans using the @Scope annotation.This helps you decide if a bean should be created once for the whole app or a new one each time it is needed.
🎯 Goal: Learn how to use the @Scope annotation to define bean scopes in Spring Boot.You will create a bean with singleton scope and then change it to prototype scope.
📋 What You'll Learn
Create a Spring Boot bean class named MyBean
Add @Component annotation to MyBean
Add @Scope annotation with ConfigurableBeanFactory.SCOPE_SINGLETON to MyBean
Change the scope to ConfigurableBeanFactory.SCOPE_PROTOTYPE using @Scope
💡 Why This Matters
🌍 Real World
Controlling bean scope is important in real applications to manage resources and behavior, like creating a new bean for each user request or sharing one bean for the whole app.
💼 Career
Understanding <code>@Scope</code> is essential for Spring developers to write efficient, maintainable, and scalable applications.
Progress0 / 4 steps
1
Create a Spring bean class with singleton scope
Create a class named MyBean in package com.example.demo. Annotate it with @Component and @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON). Import org.springframework.stereotype.Component, org.springframework.context.annotation.Scope, and org.springframework.beans.factory.config.ConfigurableBeanFactory.
Spring Boot
Need a hint?

Remember to import the correct classes and use @Component and @Scope annotations.

2
Add a simple method to MyBean
Inside the MyBean class, add a public method named getMessage that returns the string "Singleton Bean".
Spring Boot
Need a hint?

Define a public method named getMessage that returns the exact string "Singleton Bean".

3
Change the bean scope to prototype
Modify the @Scope annotation on MyBean to use ConfigurableBeanFactory.SCOPE_PROTOTYPE instead of SCOPE_SINGLETON.
Spring Boot
Need a hint?

Replace SCOPE_SINGLETON with SCOPE_PROTOTYPE inside the @Scope annotation.

4
Add a Spring Boot application class to test the bean scope
Create a class named DemoApplication in package com.example.demo. Annotate it with @SpringBootApplication. Add a main method that runs SpringApplication.run(DemoApplication.class, args). Import org.springframework.boot.SpringApplication and org.springframework.boot.autoconfigure.SpringBootApplication.
Spring Boot
Need a hint?

Create the main Spring Boot application class with @SpringBootApplication and a main method that starts the app.