springboot解决循环依赖问题
解决springBoot循环依赖问题的两个方法
·
一、报错
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌──->──┐
| com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration
└──<-──┘
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.
二、报错原因
两个类相互引用对方,导致Spring在初始化bean的时候不知道先初始化哪个,从而形成循环依赖注入。
三、解决方式
1、延迟加载
使用@Lazy 注解延迟互相依赖的其中一个bean的加载,从而解决Spring在初始化bean的时候不知道先初始化哪个的问题。
@Autowired
@Lazy // 添加该注解,延迟加载
private TokenService tokenService;
2、通过修改配置来打破循环
依赖循环引用是不鼓励的,默认情况下是禁止的。更新应用程序以删除bean之间的依赖循环。作为最后的手段,可以通过设置spring.main来自动打破循环。allow-circular-references为true。
修改yml:
spring:
main:
allow-circular-references: true
更多推荐
所有评论(0)