首页 > Java > java教程 > 正文

Spring Boot中的循环依赖

Barbara Streisand
发布: 2024-10-22 20:26:03
原创
642 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!