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

相关推荐
晴空月明38 分钟前
线程安全与锁机制深度解析
java
天天摸鱼的java工程师2 小时前
你如何处理一个高并发接口的线程安全问题?说说你做过的优化措施
java·后端
Micro麦可乐2 小时前
最新Spring Security实战教程(十八)安全日志与审计:关键操作追踪与风险预警
java·spring boot·后端·安全·spring·安全审计
刘一说3 小时前
资深Java工程师的面试题目(六)数据存储
java·开发语言·数据库·面试·性能优化
江沉晚呤时3 小时前
EventSourcing.NetCore:基于事件溯源模式的 .NET Core 库
java·开发语言·数据库
考虑考虑3 小时前
JDK17中的Sealed Classes
java·后端·java ee
写bug写bug3 小时前
深入理解Unsafe类
java·后端
星垣矩阵架构师3 小时前
六.架构设计之存储高性能——缓存
java·spring·缓存
刃神太酷啦3 小时前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
TeamDev3 小时前
在 Java 应用中构建双向数据保护
java·前端框架·全栈