LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。
目录
概述
实现思路分析
循环依赖
问题描述:Bean A依赖B,Bean B依赖A,这种情况下即为循环依赖,如下:
Bean A --> Bean B --> Bean A
导致问题:当存在循环依赖时,Spring将无法决定先创建哪个bean,这种情况下,Spring将产生异常BeanCurrentlyInCreationException。
问题
解决方案
消除循环依赖的方式是通过延迟加载,只需要在任意一个中使用@Lazy即可解决,如下:
@Component
public class E1 {
private E2 e2;
public E1(@Lazy E2 e2) {
this.e2 = e2;
}
}
@Component
public class E2 {
private E1 e1;
public E2(E1 e1) {
this.e1 = e1;
}
}
方式二
当依赖最终被使用时再进行注入是最佳的一种方式,同时这也是Spring最推荐的一种方式,如下:
@Component
public class E1 {
private E2 e2;
public void setE2(E2 e2) {
this.e2 = e2;
}
}
@Component
public class E2 {
private E1 e1;
public void setE1(E1 e1) {
this.e1 = e1;
}
}
相关工具如下:
分析:
小结:
主要讲述了@PostConstruct,InitializingBean, 里面有许多不足,请大家指正~
参考资料和推荐阅读
1.链接: 参考资料.
2.链接: 参考资料.