SpringBoot启动报 ------ The dependencies of some of the beans in the application context form a cycle错误

╰+哭是因爲堅強的太久メ 2024-03-22 20:29 284阅读 0赞

今天在启动项目的时候遇见了这样一个报错,还挺稀奇的,百度后才发现挺常见的一个错误

  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.
  3. Description:
  4. The dependencies of some of the beans in the application context form a cycle:

错误是:应用程序上下文中某些 Bean 的依赖关系形成一个循环

什么是依赖循环:

现有一个ServiceA需要调用ServiceB的方法,那么ServiceA就依赖于ServiceB,那在ServiceB中再调用ServiceA的方法,就形成了循环依赖。Spring在初始化bean的时候就不知道先初始化哪个bean就会报错。

如何解决循环依赖 :

对于代码中出现的耦合问题,解耦合的最好方法就是对现有的代码进行重构,当然我是没有选择进行重构的,因为方法要用,那这种情况下我们应该怎么做呢:

6b83a6b6ad2a40268913c3b11f0051e0.png

41338140fd634153b7385ad9dc812565.png

解决方法一:

  1. public class ClassA {
  2. @Autowired
  3. ClassB classB;
  4. }
  5. public class ClassB {
  6. @Autowired
  7. ClassA classA ;
  8. }

解决方法二:

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

解决方法三:

不使用基于构造函数的依赖注入
在字段上使用@Autowired注解,让Spring决定在合适的时机注入。
用基于setter方法的依赖注射取代基于构造函数的依赖注入来解决循环依赖。
在@Autowired注解上方加上@Lazy注解(延迟加载)

解决方法四:

代码重构,根据报错的提示重新设计类的依赖,让其中一个类不要引用对方,避免循环依赖

发表评论

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

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

相关阅读