Member-only story
Spring Singleton vs Prototype Scopes: What Every Developer Needs to Know
The two most commonly used bean scopes in the Spring Framework: singleton and prototype. Here’s a detailed breakdown of the concepts:
Singleton Scope:
In Spring, the singleton scope ensures that there is only one instance of a bean for the entire Spring container. Every time a bean is requested by its name or type, the same instance is returned.
Eager vs Lazy Initialization:
- Eager Initialization: By default, Spring creates the singleton beans when the Spring application context is initialized. This means all singleton beans are created at the startup of the application.
- Lazy Initialization: With lazy initialization, Spring delays the creation of the singleton bean until it is first referenced in the application, which can be useful for optimizing startup performance, especially for beans that might not be used immediately.
Since the singleton bean is shared across multiple threads, the bean should be designed to be immutable or thread-safe. If mutability is required, thread synchronization must be implemented to ensure thread safety when multiple threads access the bean’s attributes simultaneously.