项目场景:
新项目 本地化启动时
问题描述
项目启动中报错,错误信息如下:
2022-03-31 17:26:51.877 ERROR 24308 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| mvcConfigurer (field private org.springframework.boot.autoconfigure.http.HttpMessageConverters com.tmsj.supert.system.config.MvcConfigurer.httpMessageConverters)
↑ ↓
| messageConverters defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]
└─────┘
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.
原因分析:
类A需要通过构造函数注入的类B的实例(或者B中声明的Bean),而类B需要通过构造函数注入的类A的实例(或者A中声明的Bean)。如果将类A和类B的bean配置为相互注入,则Spring IoC容器会在运行时检测到此循环引用,并引发一个BeanCurrentlyInCreationException。与典型情况(没有循环依赖)不同,bean A和bean B之间的循环依赖关系迫使其中一个bean在被完全初始化之前被注入到另一个bean中。
解决方案:
第一种:
在 主 Application中 main方法新增,即可解决
SpringApplication springApplication = new SpringApplication(SystemApplication.class);
springApplication.setAllowCircularReferences(Boolean.TRUE);
springApplication.run(args);
第二种:
使用@Lazy注解
解决Spring 循环依赖的一个简单方法就是对一个Bean使用延时加载。也就是说:这个Bean并没有完全的初始化完,实际上他注入的是一个代理,只有当他首次被使用的时候才会被完全的初始化。
@Lazy
@Autowired
private BootSerivice bootSerivice;
第三种:
通过修改配置文件来解决
spring:
main:
allow-circular-references: true