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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号