Junior — Middle
Have you had experience with situations where mutual dependencies between beans appear in Spring?
sobes.tech AI
Answer from AI
Yes, in the Spring Framework, circular dependencies between beans can occur when two or more beans depend on each other directly or indirectly.
For example, bean A depends on bean B, and bean B depends on bean A. This causes problems during context creation because Spring cannot determine the initialization order.
To resolve such situations, you can use:
- Dependency injection via setters (
@Autowiredon methods), which allows Spring to create beans without cyclic issues. - Using
@Lazyfor deferred initialization of dependencies. - Refactoring the code to eliminate cyclic links, for example, by extracting a common dependency into a separate bean.
An example using @Lazy:
@Component
public class A {
private final B b;
public A(@Lazy B b) {
this.b = b;
}
}
@Component
public class B {
private final A a;
public B(A a) {
this.a = a;
}
}
Thus, Spring can create beans by deferring the creation of B until it is actually needed.