【报错解决】The dependencies of some of the beans in the application context form a cycle:

水深无声 2024-03-23 20:35 192阅读 0赞

问题描述

项目启动中报错,错误信息如下:

  1. 2022-03-31 17:26:51.877 ERROR 24308 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
  2. ***************************
  3. APPLICATION FAILED TO START
  4. ***************************
  5. Description:
  6. The dependencies of some of the beans in the application context form a cycle:
  7. ┌─────┐
  8. | mvcConfigurer (field private org.springframework.boot.autoconfigure.http.HttpMessageConverters com.tmsj.supert.system.config.MvcConfigurer.httpMessageConverters)
  9. | messageConverters defined in class path resource [org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.class]
  10. └─────┘
  11. Action:
  12. 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.

原因分析:

循环依赖报错

在用springboot启动项目时,报了这个互相依赖的错误,原因就是 Aservice 需要调用 Bservice ,然后Bservice 又需要调用 Aservice ,所以直接依赖循环了。

循环依赖指的是两个或者多个bean之间相互依赖,形成一个闭环。直接表现为两个service层互相调用对方。


解决方案:

第一种:

在 主 Application中 main方法新增,即可解决

  1. SpringApplication springApplication = new SpringApplication(SystemApplication.class);
  2. springApplication.setAllowCircularReferences(Boolean.TRUE);
  3. springApplication.run(args);

第二种

使用@Lazy注解
解决Spring 循环依赖的一个简单方法就是对一个Bean使用延时加载。也就是说:这个Bean并没有完全的初始化完,实际上他注入的是一个代理,只有当他首次被使用的时候才会被完全的初始化。

  1. @Lazy
  2. @Autowired
  3. private BootSerivice bootSerivice;

第三**种:**

通过修改配置文件来解决

  1. spring:
  2. main:
  3. allow-circular-references: true

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读