How does Spring resolve this: bean A is dependent on bean B, and bean B on bean A.
How does Spring resolve this: bean A is dependent on bean B, and bean B on bean A.
Circular dependency in Spring : Dependency of one Bean to other. Bean A → Bean B → Bean A
Solutions:
@Lazy Annotation@PostConstruct AnnotationIf two beans are dependent on each other then we should not use Constructor injection in both the bean definitions. Instead we have to use setter injection in any one of the beans. (of course we can use setter injection n both the bean definitions, but constructor injections in both throw 'BeanCurrentlyInCreationException'
Refer Spring doc at "https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#resources-resource"
Also we use @Lazy Annotation
@Component
public class ClassA {
private ClassB classB;
public ClassB getClassB() {
return classB;
}
@Lazy
@Autowired
public void setClassB(ClassB classB) {
this.classB = classB;
}
}
@Component
public class ClassB {
private ClassA classA;
@Autowired
public ClassB(ClassA classA) {
super();
this.classA = classA;
}
public ClassA getClassA() {
return classA;
}
public void setClassA(ClassA classA) {
this.classA = classA;
}
}