Understanding Singleton and Prototype Bean Scopes in Spring Framework
Spring Framework provides a robust dependency injection mechanism, enabling developers to manage the lifecycle of beans efficiently. Singleton and Prototype are the most commonly used among the various bean scopes available. Understanding their differences and use cases is essential for building efficient and scalable applications.
This story will explore the Singleton and Prototype scopes, their implementation, and scenarios where each is most appropriate.
What Are Bean Scopes?
A bean scope in Spring defines a bean's lifecycle and visibility in the application's context. By default, all Spring beans are singleton-scoped, but the framework offers additional scopes such as prototype, request, session, and application.
Singleton Scope
A bean with a singleton scope ensures that only one instance of the bean is created per Spring container. This instance is shared across all requests and injections within the application context.
Key Characteristics:
- Default Scope: If no scope is specified, the bean defaults to Singleton.
- Single Instance: A single instance is created and cached in the Spring container.
- Shared State: Since the same instance is shared, changes in the state of the bean can affect other parts of the application.
Implementation:
Defining a singleton bean is straightforward as it’s the default scope:
@Component
public class SingletonBean {
public SingletonBean() {
System.out.println("Singleton instance created");
}
}
In your application:
@Configuration
@ComponentScan("com.example")
public class AppConfig {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonBean bean1 = context.getBean(SingletonBean.class);
SingletonBean bean2 = context.getBean(SingletonBean.class);
System.out.println(bean1 == bean2); // Output: true
context.close();
}
}
Prototype Scope
A bean with a prototype scope creates a new instance every time it is requested from the Spring container. Unlike Singleton, the container does not manage the complete lifecycle of a prototype bean.
Key Characteristics:
- Multiple Instances: A new instance is created for each request.
- No Shared State: Each consumer gets a unique instance, avoiding unintended shared states.
- Short-Lived: The Spring container initializes the bean and hands it over, leaving further lifecycle management to the application.
Implementation:
To define a prototype-scoped bean, use the @Scope
annotation:
@Component
@Scope("prototype")
public class PrototypeBean {
public PrototypeBean() {
System.out.println("Prototype instance created");
}
}
In your application:
@Configuration
@ComponentScan("com.example")
public class AppConfig {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
PrototypeBean bean1 = context.getBean(PrototypeBean.class);
PrototypeBean bean2 = context.getBean(PrototypeBean.class);
System.out.println(bean1 == bean2); // Output: false
context.close();
}
}
Singleton vs Prototype: Key Differences
When to Use Singelton Scope
- Stateless Beans: Ideal for beans that do not maintain any internal state, such as services and controllers.
- Performance: Reduces overhead since a single instance is reused.
Example Use Case:
@Service
public class UserService {
// Business logic for user management
}
When to Use Prototype Scope
- Stateful Beans: Suitable for objects that need unique instances.
- Non-Shared Resources: When different consumers require separate instances to avoid interference.
Example Use Case:
@Component
@Scope("prototype")
public class ShoppingCart {
private List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
}
Caution: Mixing Scopes
If a Singleton-scoped bean depends on a Prototype-scoped bean, Spring injects the same prototype instance into all Singleton beans. To ensure fresh instances, use method injection.
Conclusion
Understanding the Singleton and Prototype scopes is crucial for designing Spring applications. Singleton scope is perfect for stateless shared resources, while Prototype scope is useful when multiple unique instances are required. Choose the appropriate bean scope based on the specific needs of your application to ensure optimal memory usage.
If you found this article helpful, please share your thoughts or questions in the comments below! 😊
Happy coding!