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

相关推荐
沐雪轻挽萤几秒前
2. C++17新特性-结构化绑定 (Structured Bindings)
java·开发语言·c++
java1234_小锋几秒前
Java高频面试题:Kafka的消费消息是如何传递的?
java·开发语言·mybatis
滴滴答答哒2 分钟前
c#将平铺列表转换为树形结构(支持孤儿节点作为独立根节点)
java·前端·c#
李少兄5 分钟前
Windows系统JDK安装与环境配置指南(2026年版)
java·开发语言·windows
好家伙VCC2 小时前
**神经编码新视角:用Python实现生物启发的神经信号压缩与解码算法**在人工智能飞速发展的今天
java·人工智能·python·算法
一灯架构8 小时前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
Y4090019 小时前
【多线程】线程安全(1)
java·开发语言·jvm
布局呆星10 小时前
SpringBoot 基础入门
java·spring boot·spring
不懂的浪漫10 小时前
mqtt-plus 架构解析(六):多 Broker 管理,如何让一个应用同时连接多个 MQTT 服务
spring boot·分布式·物联网·mqtt·架构
风吹迎面入袖凉10 小时前
【Redis】Redisson的可重入锁原理
java·redis