今天在学习spring底层原理的时候,了解到了循环依赖,以及三级缓存这样的解决方案,按理来说,springboot作为spring的扩展,自然来说应该是也解决了循环依赖问题了,但是我在自己写代码测试的时候,却发现如果自己定义的两个bean相互依赖,还是会报循环引用的错误,我就不是很理解?循环依赖问题难道没有没解决吗?
下面是两个Bean的定义
A.java
@Component
public class A {
@Autowired
private B b;
}
B.java
@Component
public class B {
@Autowired
private A a;
}
报错信息
Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?
按照我的理解,根据三级缓存的原理,这样应该是能成功创建Bean的,可是为什么还会报循环引用的错误呢?
因为SpringBoot从2.5+关闭了循环依赖支持,需要配置spring.main.allow-circular-references=true开启
循环依赖毕竟是不好的,仔细看看控制台输出信息,应该有提示怎么打开配置允许循环依赖
配置文件配置:
spring.main.allow-circular-references=true
在引入@Autowired 类下面加个懒加载 ( @lazy ) 比标签,随便一个加就行