Singleton Bean
About
In Spring, a singleton bean is a bean that is instantiated only once per Spring container and shared across the entire application. By default, all beans in Spring are singleton-scoped, meaning Spring creates a single instance of the bean and returns the same instance whenever it is requested.
Singleton in Spring is at the container level, not the JVM level. If multiple containers exist, each may have its own singleton instance.
How Singleton Beans Work in Spring?
When a singleton bean is defined, Spring:
Creates the bean instance once during container startup.
Stores it in a cache (BeanFactory registry).
Returns the same instance whenever the bean is requested.
Manages the lifecycle (initialization, destruction, etc.).
Example: Singleton Bean in Spring
Now, if multiple classes request this bean:
userService1
and userService2
will point to the same instance of UserService
.
Declaring Singleton Beans
By default, Spring beans are singleton-scoped. You can explicitly declare a singleton bean using:
Using @Component
(default singleton)
@Component
(default singleton)Using @Bean
in Java Configuration
@Bean
in Java ConfigurationUsing XML Configuration (Legacy)
Singleton Scope vs JVM-Level Singleton
A singleton in Java (using static
or enum
) ensures only one instance per JVM, while a Spring singleton ensures one instance per Spring container.
Comparison
Instance Count
One per Spring container
One per JVM
Lazy Loading
Yes (if configured)
No
Dependency Injection
Yes
No
Thread Safety
Managed by Spring
Needs manual handling
Flexibility
Configurable
Hardcoded
Example of a JVM singleton:
Singleton Beans in Multi-Threaded Environments
Singleton beans are shared across all threads, potentially causing race conditions.
Thread Safety Concerns
Here, count
may be inconsistent if multiple threads modify it simultaneously.
Thread-Safe Singleton
Use synchronized blocks
Use ThreadLocal variables
Use ConcurrentHashMap for shared state
Example:
Singleton Beans in Microservices (Spring Boot)
In Spring Boot, singleton beans are often used in:
Service Layer (
@Service
) – Business logic layerRepository Layer (
@Repository
) – Database interactionsController Layer (
@RestController
) – Handling HTTP requests
Example: Singleton in Microservices
Here, OrderService
is singleton, ensuring a single instance handles all requests.
Last updated
Was this helpful?