当前位置: 首页 > 图灵资讯 > 技术篇> 解决SpringBoot循环依赖问题

解决SpringBoot循环依赖问题

来源:图灵教育
时间:2023-05-09 10:06:09

 

一、报错

The dependencies of some of the beans in the application context form a cycle:   documentationPluginsBootstrapper defined in URL [jar:file:/D:/maven/repository/io/springfox/springfox-spring-web/3.0.0/springfox-spring-web-3.0.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]      ↓   webMvcRequestHandlerProvider defined in URL [jar:file:/D:/maven/repository/io/springfox/springfox-spring-webmvc/3.0.0/springfox-spring-webmvc-3.0.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]      ↓   org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration┌─────┐|  com.alibaba.cloud.sentinel.SentinelWebAutoConfiguration (field private java.util.Optional com.alibaba.cloud.sentinel.SentinelWebAutoConfiguration.sentinelWebInterceptorOptional)└─────┘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时不知道先初始化的问题。

2、通过修改配置来打破循环

不建议引用循环依赖。默认情况是禁止的。更新应用程序以删除bean之间的依赖循环。作为最终手段,循环可以通过设置自动打破。

spring:main:  allow-circlar-references: true

上一篇:

Java SE整体总结

下一篇:

异常的基本用法