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

相关推荐
sunwenjian8866 分钟前
Spring Boot 整合 Druid 并开启监控
java·spring boot·后端
1104.北光c°11 分钟前
基于Canal + Kafka的高可用关注系统:一主多从关系链
java·开发语言·笔记·分布式·程序人生·kafka·一主多从
Mem0rin12 分钟前
[Java]异常及其处理
java·开发语言
skiy13 分钟前
Spring boot创建时常用的依赖
java·spring boot·后端
码路星河15 分钟前
SpringBoot3 动态扩展实战:不重启服务,轻松插拔业务模块
spring boot
早起的年轻人15 分钟前
告别Git仓库臃肿:一招解决Maven target目录误提交问题
java·git·maven
快乐柠檬不快乐21 分钟前
Java连接电科金仓数据库(KingbaseES)实战指南
java·开发语言·数据库
程序员清风23 分钟前
看完Anthropic研究才懂:你有多会问,AI就有多强!
java·后端·面试
爱学习的小囧24 分钟前
VCF 集群部署灵活组合:单节点与高可用配置完全指南
java·服务器·前端
代码方舟29 分钟前
Java金融风控实战:集成天远二手车估值API构建车贷抵押资产核验系统
java·开发语言·python·自动化