java 中的循环依赖是指两个类或两个模块相互依赖,从而形成循环。
假设我们有两个相互依赖的 bean a 和 b,如下例所示:
@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;
}
}
运行项目时,会出现以下错误:
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.
因此,为了解决这种循环依赖,我们有四种解决方案:
- 重构代码以分离职责。
- 使用中间类或接口。
- 通过方法(setter)应用依赖注入。
- 使用 @lazy 等注解来延迟初始化。

在我们的例子中,我们将使用第四种解决方案,即使用注释@lazy,如下例所示:
@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;
}
}
我们现在已经脱离了这个循环:)








