一、报错

***************************
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
Logo

欢迎加入西安开发者社区!我们致力于为西安地区的开发者提供学习、合作和成长的机会。参与我们的活动,与专家分享最新技术趋势,解决挑战,探索创新。加入我们,共同打造技术社区!

更多推荐