In Spring, singleton beans and their dependencies are initialized when the application context is created.
If a Singleton
bean depends on a bean with a shorter-lived scope (like Request
or Session
beans), it retains
the same instance of that bean, even when new instances are created for each Request or Session. This mismatch can cause unexpected behavior and bugs,
as the Singleton bean doesn’t interact correctly with the new instances of the shorter-lived bean.
This rule raises an issue when non-singleton beans are injected into a singleton bean.
What is the potential impact?
When a Singleton
bean has a dependency on a bean with a shorter-lived scope, it can lead to the following issues:
- Data inconsistency: any state change in the shorter-lived bean will not be reflected in the Singleton bean.
- Incorrect behavior: using the same instance of the shorter-lived bean, when a new instance is supposed to be created for each
new request or session.
- Memory leaks: preventing garbage collection of a shorter-lived bean that allocates a significant amount of data over time.