今天在启动项目的时候遇见了这样一个报错,还挺稀奇的,百度后才发现挺常见的一个错误
Action:
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.
Description:
The dependencies of some of the beans in the application context form a cycle:
错误是:应用程序上下文中某些 Bean 的依赖关系形成一个循环
什么是依赖循环:
现有一个ServiceA需要调用ServiceB的方法,那么ServiceA就依赖于ServiceB,那在ServiceB中再调用ServiceA的方法,就形成了循环依赖。Spring在初始化bean的时候就不知道先初始化哪个bean就会报错。
如何解决循环依赖 :
对于代码中出现的耦合问题,解耦合的最好方法就是对现有的代码进行重构,当然我是没有选择进行重构的,因为方法要用,那这种情况下我们应该怎么做呢:
解决方法一:
public class ClassA {
@Autowired
ClassB classB;
}
public class ClassB {
@Autowired
ClassA classA ;
}
解决方法二:
spring:
main:
allow-circular-references: true
解决方法三:
不使用基于构造函数的依赖注入
在字段上使用@Autowired注解,让Spring决定在合适的时机注入。
用基于setter方法的依赖注射取代基于构造函数的依赖注入来解决循环依赖。
在@Autowired注解上方加上@Lazy注解(延迟加载)
解决方法四:
代码重构,根据报错的提示重新设计类的依赖,让其中一个类不要引用对方,避免循环依赖