要解释循环依赖首先要从bean的生命周期说起:
1、createBean()实例化bean
2、属性赋值(依赖注入)
3、beanpostProcessor前置扩展
4、init-method初始化bean方法
5、beanpostProcessor后置扩展
6、使用
7、销毁
大体思路:
Spring中解决循环依赖使用了三个map,singletonObjects(一级缓存单例池)\earlySingletonObjects(三级缓存)\singletonFactories(二级缓存)
class A{B b;}
class B{A a;}
第一步 A实例化完成,进行属性注入需要B,所以此时将B实例化对B进行属性注入获取到A的实例化对象。注意这个位置,此时注入的并不是A的实例化对象,而是从二级缓存singletonFactories中拿到的工厂对象。所以A的后续扩展和初始化操作都是在工厂中完成然后B执行后续的扩展方法和初始化方法。至此完成了一个完整的循环依赖
缓存机制核心源码
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
//当前方法解决了spring的循环依赖
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//singletonObjects单例池--》第一个缓存map中取bean,第一次来单例池中肯定没有
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//earlySingletonObjects-->第三个缓存map
//为什么要有这第三个缓存,直接返回第二个缓存不就好了?
//Spring这是为了性能最大化,不需要每次都进factory里面
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//singletonFactories--》第二个缓存池,从factory里面拿到的bean还是一个半成品
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//从factory中拿到半成bean,放到第三个缓存map中,并且把第二个中的bean删除
//bean在三个缓存map中,只存在一份
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}