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

相关推荐
IT199514 分钟前
Java文档阅读笔记-AI LangChain4j - Agent Multiple Tools Calling Example
java·笔记·文档阅读
rlpp20 分钟前
spring.profiles.active和spring.profiles.include的使用及区别说明
java·后端·spring
Pluchon21 分钟前
硅基计划4.0 算法 简单实现B树
java·数据结构·b树·算法·链表
whatever who cares1 小时前
Java Web 架构全组件详解
java·前端·架构
好家伙VCC1 小时前
**标题:发散创新|用Python构建GAN图像生成器:从理论到实战全流程解析**---在深度学习飞速发展的今天,**生成对抗
java·python·深度学习·生成对抗网络
我命由我123451 小时前
Android Studio - 在 Android Studio 中直观查看 Git 代码的更改
android·java·开发语言·git·java-ee·android studio·android jetpack
苏荷水1 小时前
万字总结LeetCode100(持续更新...)
java·算法·leetcode·职场和发展
不光头强2 小时前
SpringBoot 开发第三天 学习内容
java·spring boot·学习
黎雁·泠崖2 小时前
【魔法森林冒险】12/14 场景系统:5大场景的任务串联
java·开发语言