首页  >  文章  >  Java  >  Spring Boot中的循环依赖

Spring Boot中的循环依赖

Barbara Streisand
Barbara Streisand原创
2024-10-22 20:26:03647浏览

Dépendances cycliques en spring boot

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;
    }
}

我们现在已经脱离了这个循环:)

以上是Spring Boot中的循环依赖的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn