【Spring成神之路】从源码角度深度刨析Spring循环依赖
在Spring框架中,循环依赖是指两个或多个Bean相互依赖对方,形成闭环,导致无法正常创建Bean的情况。Spring解决循环依赖的关键在于提前暴露一个Bean的引用,使得后续Bean可以引用该Bean,从而打破循环依赖。
以下是Spring解决循环依赖的核心步骤:
- 创建Bean实例,但不初始化属性。
- 暴露一个代理对象(Bean的原型),使得其他Bean能引用该Bean。
- 初始化Bean,设置属性。
以下是Spring处理循环依赖的核心源码:
public class DefaultSingletonBeanRegistry {
// 存储Bean名称和Object的关系
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
// 存储Bean名称和ObjectFactory的关系,用于创建Bean
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>();
// 对应的Bean正在创建中
private final Set<String> singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet<>());
// 获取Bean,如果Bean正在创建中,则从singletonFactories获取早期的引用
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && this.singletonsCurrentlyInCreation.contains(beanName)) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
// 注册单例Bean,将Bean添加到singletonFactories
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.singletonsCurrentlyInCreation.add(beanName);
}
}
}
// 注册单例Bean,将Bean添加到singletonObjects
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonsCurrentlyInCreation.remove(beanName);
this.singletonFactories.remov
评论已关闭