1、一级缓存:经历完整的springbean生命周期,保存已完成初始化的bean
2、二级缓存:保存正在初始化的bean(实例化完成没有注入属性),解决springbean的循环依赖
3、三级缓存:保存的时初始化完成的bean的工厂,解决springaop代理的循环依赖
工作过程:
1、当ABean实例化完成后,加入三级缓存,进入ABean初始化阶段,发现依赖BBean
2、当BBean实例化完成后,加入三级缓存,进入BBean初始化阶段,发现依赖ABean
3、BBean发现在ABean在三级缓存中刚好有,利用工厂缓存完成ABean的创建(ABean实例化完成但未赋值),存入二级缓存,删除三级缓存。
4、BBean完成了ABean的依赖注入(ABean就是个半成品,初始化了工厂缓存,实例化但没有赋值),证明BBean初始化完成,BBean放入到一级缓存。
5、ABean发现在BBean在一级缓存中,继续对BBean的赋值,也完成了初始化。
二级缓存就可以解决循环依赖了,
DefaultSingletonBeanRegistry#getSingleton
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
/** Cache of singleton factories: bean name --> ObjectFactory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
/** Cache of early singleton objects: bean name --> bean instance */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
/**
* 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
*/
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
三级缓存因为springaop特性,代理也会发生循环依赖的场景
proxy提前存入工厂缓存,实例化之前早早暴露出来。
AbstractAutowireCapableBeanFactory#doCreateBean
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}