程序开发 · 2024年10月11日

Spring Boot中的循环依赖

Spring Boot中的循环依赖

收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是文章学习者,那么本文《Spring Boot中的循环依赖》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

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中的循环依赖》文章吧,也可关注公众号了解相关技术文章。

版本声明 本文转载于:dev.to 如有侵犯,请联系删除