spring中循环依赖有三种情况:
1、构造器注入形成的循环依赖。这种难以解决
2、setter注入构成的循环依赖,可以解决
3、prototype作用域的循环依赖。这种循环依赖同样无法解决。
解决循环依赖主要依赖singletonFactories、earlySingletonObjects和singletonObjects
时序图如下:
bean的创建在首次创建时,因为不在singletonObjects并且不在创建中时会执行下面语句
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
创建时,如果设置了允许循环依赖,则将生成的对象的工厂方法添加到singletonFactories中
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, () -> getEarlyBeanReference(beanName, mbd, bean));
}
在第二次获取时,会调用如下,将singletonFactories移动到earlySingletonObjects
在创建完成后,会从singletonsCurrentlyInCreation中删除,将对象从earlySingletonObjects移动到singletonObjects