Error: The dependencies of some of the beans in the application context form a cycle

Error: The dependencies of some of the beans in the application context form a cycle

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:

  1. Review the dependencies between the beans mentioned in the error message.
  2. Ensure that no circular imports are present in the java class, as this can cause the cyclic dependency issue.
  3. Configure the followings in application.property file to address the issue
    spring.main.allow-bean-definition-overriding=true
    spring.main.allow-circular-references=true
  4. 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;
}
}


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *