-
原型模式下的循环依赖是无法无法解决的
-
构造方法注入 + 单例模式,仅可以通过延迟加载解决
-
setter 方法和属性注入 + 单例模式下,可以解决
核心逻辑如下:
AbstractAutowireCapableBeanFactory.allowCircularReferences=true
通过三级缓存(或者说三个 Map 去解决循环依赖的问题),核心代码在 DefaultSingletonBeanRegistry#getSingleton
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//Map 1,单例缓存
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//Map 2,早期单例缓存,若没有 ObjectFactory 的 bean,到这级已经可以解决循环依赖
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//Map 3,单例工厂,解决包含 ObjectFactory 情况的循环依赖
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();//获取 bean 对象
this.earlySingletonObjects.put(beanName, singletonObject);//放到早期实例化的 Bean 中
this.singletonFactories.remove(beanName);//单例工厂中移除
}
}
}
}
return singletonObject;
}