SpringBoot中循环依赖报错解决---The dependencies of some of the beans in the application context form a cycle

深碍√TFBOYSˉ_ 2024-04-03 11:24 287阅读 0赞

循环依赖:

循环依赖就是循环引用,也就是两个或则两个以上的bean互相依赖对方,形成闭环。比如A类中有B属性,B类中有A属性

一、报错信息

The dependencies of some of the beans in the application context form a cycle:

99fe33727749422ea65f0dc67e1419c0.png

二、解决方案

1、修改配置文件

根据Action中的提示

  1. Action:
  2. 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.

不鼓励依赖循环引用,默认情况下禁止循环引用。更新应用程序以删除 Bean 之间的依赖关系循环。作为最后的手段,可以通过将 spring.main.allow-circular-references 设置为 true 来自动打破循环。因此可以在yml配置文件中设置来打破循环依赖

修改yml

  1. spring:
  2. main:
  3. allow-circular-references: true

2、添加注解,延迟加载

这个是网上找到的解决方案,经过测试,问题顺利解决

由于在循环依赖中,Spring在初始化的时候不知道先加载哪个bean,因此可以通过使用@Lazy注解,放在其中一个bean上,让这个bean延迟加载,另一个bean就会先加载,进而解决循环依赖问题

45871751036d4162903c4590aa97bdac.png

发表评论

表情:
评论列表 (有 0 条评论,287人围观)

还没有评论,来说两句吧...

相关阅读