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

相关推荐
怒放吧德德4 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆6 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌8 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
初次攀爬者9 小时前
Kafka 基础介绍
spring boot·kafka·消息队列
华仔啊9 小时前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang9 小时前
用六边形架构与整洁架构对比是伪命题?
java·架构
用户8307196840829 小时前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Ray Liang11 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Java水解11 小时前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
Java水解11 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端