spring 使用三级缓存解决循环依赖详解

发布于:2025-07-30 ⋅ 阅读:(18) ⋅ 点赞:(0)

前言

在spring 2.6之前的版本中,默认都是支持循环依赖的,也就不会报错,在2.6版本之后默认禁用了循环依赖;可通过以下方式开启循环依赖

spring:
  main:
    allow-circular-references: true # 开启循环依赖, false (默认)表示禁用循环依赖

复现

比如有以下2个类,A引用了B,B引用了A;

A.java

@Service
public class B{
 @Autowried
  private B b;
}

B.java

@Service
public class B{
 @Autowried
  private A a;
}

默认情况下启动spring就会抛出循环依赖的异常

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  a (field private com.spring.service.B com.spring.service.A.b)
↑     ↓
|  b (field private com.spring.service.A com.spring.service.B.a)
└─────┘


Action:

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.

三级缓存

先说下三级缓存的作用

  • 一级缓存:实例化且属性已注入完成的Bean
  • 二级缓存:
    在这里插入图片描述

三级缓存的执行流程如下:
在这里插入图片描述

解决

这里有2种解决方案

1、添加懒加载注解 @Lazy

用法如下

@Service
public class B {

    @Autowired
    @Lazy
    private A a;
}

2、启用循环依赖的配置

在application.yml 文件加上以下配置即可

spring:
  main:
    allow-circular-references: true

网站公告

今日签到

点亮在社区的每一天
去签到