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.
因此,为了解决这种循环依赖,我们有四种解决方案:
在我们的例子中,我们将使用第四种解决方案,即使用注释@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; } }
我们现在已经脱离了这个循环:)
以上是Spring Boot中的循环依赖的详细内容。更多信息请关注PHP中文网其他相关文章!