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来解决问题。

相关推荐
是梦终空27 分钟前
JAVA毕业设计253—基于Java+Springboot+vue3+协同过滤推荐算法的传统服饰文化平台(源代码+数据库+任务书+12000字论文)
java·spring boot·vue·毕业设计·课程设计·协同过滤推荐算法·传统服饰文化平台
HerayChen8 小时前
HbuilderX 内存溢出报错
java·大数据·linux
程序员小白条8 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
小马爱打代码8 小时前
Spring AI:搭建自定义 MCP Server:获取 QQ 信息
java·人工智能·spring
郭涤生8 小时前
QT 架构笔记
java·数据库·系统架构
韩立学长8 小时前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
daidaidaiyu8 小时前
基于LangGraph开发复杂智能体学习一则
java·ai
小小8程序员9 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
a努力。9 小时前
Redis Java 开发系列#2 数据结构
java·数据结构·redis
a努力。10 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构