@Scope Annotation in Spring: Definition and Usage
@Scope annotation in Spring 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 or prototype scope.How It Works
The @Scope annotation tells Spring how to manage the lifecycle of a bean. Think of it like deciding how many copies of a book to keep in a library. If you keep only one copy (singleton), everyone shares it. If you keep many copies (prototype), each person gets their own.
By default, Spring creates one shared instance of a bean (singleton). Using @Scope, you can change this to create a new instance every time the bean is requested (prototype), or other scopes like request or session in web apps.
This helps control resource use and behavior depending on how you want your components to act in your app.
Example
This example shows a simple Spring bean with @Scope("prototype"). Each time the bean is requested, a new instance is created.
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: " + this); } } // Usage in a Spring application context import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class ScopeExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("your.package"); MyBean bean1 = context.getBean(MyBean.class); MyBean bean2 = context.getBean(MyBean.class); System.out.println("bean1 == bean2? " + (bean1 == bean2)); context.close(); } }
When to Use
Use @Scope when you need control over how many instances of a bean exist and how long they live. For example:
- Singleton scope (default): When you want one shared instance for efficiency and consistency.
- Prototype scope: When each use needs a fresh instance, like for stateful objects.
- Request or session scopes in web apps: To tie bean lifecycles to HTTP requests or user sessions.
This helps manage memory, thread safety, and behavior depending on your app’s needs.
Key Points
@Scopecontrols bean lifecycle and instance count in Spring.- Default scope is singleton, meaning one shared instance.
- Prototype scope creates a new instance each time the bean is requested.
- Other scopes like request and session are useful in web applications.
- Choosing the right scope helps manage resources and application behavior.
Key Takeaways
@Scope defines how many bean instances Spring creates and how long they live.@Scope is not specified.