解释一下spring如何解决循环依赖 并贴出相关源代码
时间: 2023-05-19 12:05:10 浏览: 100
Spring通过三级缓存解决循环依赖问题。当Spring创建一个Bean时,它会将该Bean放入第一级缓存中,然后检查该Bean所依赖的其他Bean是否已经创建,如果已经创建,则将这些Bean注入到该Bean中。如果其他Bean还没有创建,则将该Bean放入第二级缓存中,等待其他Bean创建完成后再进行注入。如果其他Bean也依赖于该Bean,则将该Bean放入第三级缓存中,等待其他Bean创建完成后再进行注入。
以下是相关的源代码:
```
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
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;
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
}
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
}
}
}
```
请注意,这只是Spring中解决循环依赖问题的一部分代码。完整的代码可以在Spring源代码中找到。
阅读全文