1. What Is a Circular Dependency?
It happens when a bean A depends on another bean B, and the bean B depends on the bean A as well:
Bean A → Bean B → Bean A
Of course, we could have more beans implied:
Bean A → Bean B → Bean C → Bean D → Bean E → Bean A
Circular dependency is a design smell, either fix it or use @Lazy for the dependency which causes problem to workaround it.
@Component
public class CircularDependencyA {
private CircularDependencyB circB;
@Autowired
public CircularDependencyA(CircularDependencyB circB) {
this.circB = circB;
}
}
@Component
public class CircularDependencyB {
private CircularDependencyA circA;
@Autowired
public CircularDependencyB(CircularDependencyA circA) {
this.circA = circA;
}
}
Solution
Use @Lazy
A simple way to break the cycle is saying Spring to initialize one of the beans lazily.
@Component
public class CircularDependencyA {
private CircularDependencyB circB;
@Autowired
public CircularDependencyA(@Lazy CircularDependencyB circB) {
this.circB = circB;
}
}
No comments:
Post a Comment