本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

SpringBoot中的循环依赖

网络教程 app 1℃

SpringBoot中的循环依赖

java 中的循环依赖是指两个类或两个模块相互依赖,从而形成循环。

假设我们有两个相互依赖的 bean a 和 b,如下例所示:

@ponentpublic class a{ private final b b; public a(b b){ this.b = b; }}

@ponentpublic 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,如下例所示:

@ponentpublic class a{ private final b b; public a(@lazy b b){ this.b = b; }}

@ponentpublic class b{ private final a a; public b(a a){ this.a = a; }}

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

以上就是Spring Boot中的循环依赖的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » SpringBoot中的循环依赖

喜欢 (0)