A cyclical dependency occurs in Java when two classes or two modules depend on each other, thus forming a cycle.
Suppose we have two beans A and B which depend on each other as shown in the example below:
@Component public class A{ private final B b; public A(B b){ this.b = b; } }
@Component public class B{ private final A a; public B(A a){ this.a = a; } }
When running your project, you will get the following error:
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.
So, to resolve this cyclic dependency, we have four solutions:
In our case, we will use the fourth solution which is just to use the annotation @lazy as shown in the example below:
@Component public class A{ private final B b; public A(@Lazy B b){ this.b = b; } }
@Component public class B{ private final A a; public B(A a){ this.a = a; } }
And there we are, we are now out of this cycle :)
The above is the detailed content of Cyclic dependencies in spring boot. For more information, please follow other related articles on the PHP Chinese website!