This error message designates that there is a cyclic dependency between beans in the spring application. This usually happens when one bean depends on the other and that bean directly or indirectly calls the first bean.
For Example:
@Component
public class CyclicDependencyA {
private CyclicDependencyB cyclicB;
@Autowired
public CyclicDependencyA(CyclicDependencyB cyclicB) {
this.cyclicB=cyclicB;
}
}
@Component
public class CyclicDependencyB {
private CyclicDependencyA cyclicA;
@Autowired
public CyclicDependencyB(CyclicDependencyA cyclicA) {
this.cyclicA=cyclicA;
}
}
In the above example, we are using Constructor-based injection. In latest versions of Spring, the container will detect circular dependencies regardless of whether you’re using a field/Constructor-setter based injection.
Here are some solutions to address the issue:
- Review the dependencies between the beans mentioned in the error message.
- Ensure that no circular imports are present in the java class, as this can cause the cyclic dependency issue.
- Configure the followings in application.property file to address the issue
spring.main.allow-bean-definition-overriding=true
spring.main.allow-circular-references=true - Use @Lazy annotation on one of the beans involved in the cycle.
@Componentpublic
class CyclicDependencyA
{
private CyclicDependencyB cyclicB;
@Autowired@Lazypublic
CyclicDependencyA(CyclicDependencyB cyclicB)
{
this.cyclicB=cyclicB;
}
}