java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > spring使用三级缓存解决循环依赖

spring使用三级缓存解决循环依赖的情况

作者:java叶新东老师

Spring 2.6后默认禁用循环依赖,启动时报错;可通过@Lazy注解或配置启用,三级缓存分别存储完整Bean、部分注入对象和未注入对象,解决依赖注入问题

前言

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

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

复现

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

@Service
public class B{
 @Autowried
  private B b;
}
@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.

三级缓存

先说下三级缓存的作用

解决

这里有2种解决方案

1、添加懒加载注解 @Lazy

用法如下

@Service
public class B {

    @Autowired
    @Lazy
    private A a;
}

2、启用循环依赖的配置

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

spring:
  main:
    allow-circular-references: true

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文