springboot升级出现循环依赖问题

背景

问题从spring boot 2.3.12升级到2.6.15版本后,项目启动后访问报错.

The dependencies of some of the beans in the application context form a cycle.

serviceCollectionIdCacheService

┌─────┐

| serviceProductInfoProviderImpl

↑ ↓

| serviceOfflineProviderImpl

↑ ↓

| serviceProductMappingProviderImpl

└─────┘

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.

原因

在2.6.0之前,spring会自动处理循环依赖的问题,2.6.0 以后的版本默认禁止 Bean 之间的循环引用,如果存在循环引用就会启动失败报错。

解决

方案1

清理循环引用的Bean

1、在字段上使用@Autowired注解,让Spring决定在合适的时机注入。

2、在@Autowired注解上方加上@Lazy注解(延迟加载)

(A--->B--->C--->D 一般在D引用A的@Autowired下加入@Lazy注解即可)

方案2

it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

也可以暂时跳过,在yml配置中加入

复制代码
spring:
  main:
    allow-circular-references: true

方案3

在启动中加入也一样

java 复制代码
public static void main(String[] args) {
  SpringApplication sa = new SpringApplication(xx.class);
  sa.setAllowCircularReferences(Boolean.TRUE);//加入的参数
  sa.run(args);
}

本人采用了方案3来解决问题。

相关推荐
次次皮几秒前
代理启动前端dist包
java·前端·vue
zmsofts3 分钟前
Maven核心能力深度解析:从项目管理到扩展机制
java·python·maven
段ヤシ.6 分钟前
回顾Java知识点,面试题汇总Day5(持续更新)
java·开发语言
不会C语言的男孩16 分钟前
C++ SLTL编程
java·开发语言·c++
java修仙传18 分钟前
Java 实习日记:从业务表关系到节点价格分析接口改造
java·开发语言·实习
码农-阿杰31 分钟前
Java 线程等待唤醒机制深度解析:synchronized、ReentrantLock、LockSupport 底层实现对比
java·开发语言·c++
数字化顾问42 分钟前
(122页PPT)企业数字化IT架构蓝图规划设计方案(附下载方式)
java·运维·架构
不是光头 强1 小时前
Spring Boot 多线程场景下 i18n 国际化失效问题排查与解决
java·开发语言·springboot
勿忘,瞬间1 小时前
Spring IOC and DI
java·spring
小坏讲微服务1 小时前
SpringBoot4.0整合Spring Security+MyBatis Plus完整权限框架实现
java·spring·mybatis·spring security·mybatis plus·springboot4.0