Solve - Spring Circular Reference
What is a Spring Circular Reference?
A circular reference in Spring occurs when two or more beans depend on each other, causing Spring to be unable to determine which bean should be created first. This issue arises in the context of Dependency Injection (DI), which can be implemented in three ways: Setter Injection, Field Injection, and Constructor Injection.
Circular References with Different Injection Types
- Setter and Field Injection:
- Circular reference issues do not occur during application loading with Setter or Field Injection.
- This is because dependencies are injected only when the bean is actually used (e.g., when a method is called), not during the bean creation phase. As a result, circular reference problems manifest at runtime when the relevant method is invoked.
- Constructor Injection:
- Circular references do occur during application loading with Constructor Injection.
- This happens because Spring must inject the referenced beans at the time of bean creation. In a circular reference scenario, Bean A depends on Bean B, and Bean B depends on Bean A, leading to an infinite loop of dependency injection.
Background
The issue was encountered after implementing remember-me with Spring Security, where a circular reference occurred between accountService and securityConfig. Both components were endlessly attempting to inject each other, resulting in a circular dependency.
Analysis
Solution
By moving those two Beans to Appconfig, the problem was solved.
Comments
Post a Comment