在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;

本文介绍了SpringBoot2.6版本后,由于bean循环引用可能导致启动报错的问题。文章详细阐述了报错原因、官方建议的解决方案,包括设置`spring.min.allow-circular-references`以及三种依赖注入方式:构造方法、set方法和属性注入(不推荐)。
5280

被折叠的 条评论
为什么被折叠?



