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

相关推荐
古法老登瞎折腾4 小时前
大数据智能运维实战(一):机器和任务数据都有了,如何用 MCP 搭建运维助手?
大数据·运维·spring boot·spring ai·mcp
开开心心就好4 小时前
多份文档怎么批量打印?支持多种格式
java·服务器·开发语言·pdf·ocr·散列表·启发式算法
Pniubi5 小时前
模拟一个充值送token怎么保证幂等?一致性?原子性?
java
企业数字化笔记5 小时前
多租户配额怎么控制?用量口径、并发预留与超额处理的实现方法
java·数据库·spring boot
巴勒个啦5 小时前
Prompt Engineering 实战:5 个让 AI 生成生产级业务代码的工程模式
java·前端
倚楼听风语5 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
开开心心就好6 小时前
文件被占用删不掉?解锁工具强制删除
java·运维·服务器·开发语言·前端·pdf·ocr
weixin_460443566 小时前
Java+Linux私有化训考平台:服务、数据库与终端部署结构解析
java·linux·数据库·私有化部署·企业培训考试系统·企业考试系统
云和数据.ChenGuang6 小时前
python大小整数范围解析
java·开发语言·python
Java内核笔记6 小时前
Spring AI 生产级 Chat 接口:6 个开关、13 个坑,其中 2 个开关根本没生效
java·人工智能·后端