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

相关推荐
xieliyu.3 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
星辰徐哥3 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥3 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约3 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee3 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐3 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs3 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐3 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司3 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
一条小锦吕*3 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化