I've read that to resolve circular dependency we should either use setter or field injection. I tried both but I still have the same issue. I am using spring boot app : java17/spring 3.1.5.
- Setter injection
BeanA
@Component
public class BeanA {
BeanA() {
System.out.println("BeanA constructor called !!!");
}
private BeanB beanB;
@Autowired
public void setBeanB(BeanB beanB) {
System.out.println("Setting property beanB of BeanA instance");
this.beanB = beanB;
}
}
BeanB
@Component
public class BeanB {
BeanB() {
System.out.println("BeanB constructor called !!!");
}
private BeanA beanA;
@Autowired
public void setBeanA(BeanA beanA) {
System.out.println("Setting property beanA of BeanB instance");
this.beanA = beanA;
}
}
- Field injection
BeanA
@Component
public class BeanA {
@Autowired
BeanB beanB;
BeanA(){
// System.out.println("beanA init!");
}
}
Bean B
@Component
public class BeanB {
@Autowired
BeanA beanA;
BeanB(){
System.out.println("beanB init!");
}
}
for both examples I get the following error
**************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| beanA
↑ ↓
| beanB
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
below is the hierarchy of the app
com.demo.example
MainApp.java
setterInjection
..beanA
..beanB
fieldIjection
..beanA
..beanB
You can try adding following values in application.properties/yaml file: spring.main.allow-circular-references=true