在springboot2.6以后,因bean之间循环引用会导致启动报错的问题。
1.报错详细信息
其实从报错信息可以看出,java已经对问题和解决方案给出了详细说明。
注意:
不鼓励依赖循环引用,并且默认情况下禁止循环引用。更新应用程序以删除bean之间的依赖循环。作为最后的手段,可以通过将spring.min.allow-circular-references=true来设置循环依赖。
2.解决方案
按照官方给出的建议,有如下三种解决方案。需要调整配置信息。
spring.min.allow-circular-references=true
- 基于构造函数的依赖注入
- 基于set方法的依赖注入
- 基于属性的依赖注入
以下是不同依赖注入的具体写法:
1) 基于构造方法的依赖注入
private DataStatisticsMapper dataStatisticsMapper;
public TestDataStatisticsService(DataStatisticsMapper dataStatisticsMapper) {
this.dataStatisticsMapper = dataStatisticsMapper;
}
2) 基于set方法的依赖注入(set方法需要加@Autowired注解)
//通过set方法注入依赖,解决循环依赖
private IMonthDetailService monthDetailService;
@Autowired
public void setMonthDetailService(IMonthDetailService monthDetailService) {
this.monthDetailService = monthDetailService;
}
3)基于属性的依赖注入,使用@Autowired注解(不推荐,开发工具会提示)
@Autowired
private IYearChildService yearChildService;