Bean Scope in Spring Boot: What It Is and How It Works
bean scope defines the lifecycle and visibility of a bean within the application context. It controls how many instances of a bean are created and how long they live, such as singleton (one instance per app) or prototype (new instance each time).How It Works
Think of a bean in Spring Boot as a reusable object that your app needs to work. The bean scope decides how many copies of this object exist and how long each copy stays alive. For example, a singleton scope means there is only one shared object used everywhere, like a single coffee machine in an office that everyone uses.
On the other hand, a prototype scope means a new object is created every time it is needed, like giving each person their own coffee mug. This helps manage resources and behavior depending on what your app needs. Spring Boot manages these scopes automatically so you don’t have to create or destroy objects manually.
Example
This example shows how to define a bean with prototype scope in Spring Boot. Each time you ask for the bean, Spring creates a new instance.
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class MyBean { public MyBean() { System.out.println("MyBean instance created"); } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class DemoApplication implements CommandLineRunner { @Autowired private ApplicationContext context; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) throws Exception { MyBean bean1 = context.getBean(MyBean.class); MyBean bean2 = context.getBean(MyBean.class); System.out.println("bean1 == bean2: " + (bean1 == bean2)); } }
When to Use
Use singleton scope when you want one shared instance of a bean across your whole app, such as for services or configuration objects. This saves memory and keeps data consistent.
Use prototype scope when you need a fresh instance every time, like for objects that hold temporary data or user-specific info. Other scopes like request or session are useful in web apps to tie bean lifetimes to HTTP requests or user sessions.
Key Points
- Singleton is the default scope, creating one shared bean instance.
- Prototype creates a new bean instance each time it is requested.
- Web scopes like
requestandsessionmanage beans per HTTP request or user session. - Choosing the right scope helps manage memory and behavior efficiently.