本文基于spring4.3.9
什么是循环依赖
在spring中一个bean依赖另外一个bean有两种方式,一是通过构造函数,二是通过字段注入。
用代码来解释循环依赖,那么就是以下场景
public class A{
@Autowired
B b;
}
public class B{
@Autowired
A a;
}
或者
public class A{
public A(B b){
}
}
public class B{
public B(A a){
}
}
也可以是
public class A{
public A(B b){
}
}
public class B{
@Autowired
A a;
}
如何解决
循环依赖只存在于singleton类型bean之间
对于构造函数循环依赖的情况,spring无能为力,在获取bean前spring中会通过下面代码抛出异常
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
singletonsCurrentlyInCreation会保存当前正在构造中的beanName,错误产生逻辑大概如下:
- 我们向BeanFactory获取A类型的bean
- A类型bean准备构造,把beanName保存到singletonsCurrentlyInCreation
- A类型通过构造函数实例化,依赖B类型的Bean,向BeanFactory请求B类型Bean
- B类型bean准备构造,把beanName保存到singletonsCurrentlyInCreation
- B类型通过构造函数实例化,依赖A类型的Bean,向BeanFactory请求A类型Bean
- 在DefaultSingletonBeanRegistry#getSingleton#beforeSingletonCreation方法的检查singletonsCurrentlyInCreation是否已经包含当前请求的beanName,抛出异常
而对于字段注入类型或者字段注入和构造函数混合的循环依赖,spring通过缓存解决这个问题。因为其中一个对象是可实例化的!!
我们以字段注入类型的循环依赖为例
- 我们向BeanFactory获取A类型的bean
- A类型bean实例化,把未初始化的自己放到缓存中
- A类型bean进行构造(populdateBean),触发了依赖注入B
- 我们向BeanFactory获取B类型的bean
- B类型bean实例化,把未初始化的自己放到缓存中
- B类型bean进行构造(populdateBean),触发了依赖注入A
- 从二级缓存中获取到未初始化的A
- B类型bean进行初始化,返回给第3步的A进行依赖注入
- A类型bean进行初始化
- 返回给调用getBean的方法
这个缓存我们称它为三级缓存,它的代码如下,会在doGetBean的开头被调用
//DefaultSingletonBeanRegistry#getSingleton
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//singletonObjects 第一级缓存,BeanFactory的单例全存在singletonObjects中
//保存的是已经初始化完全的单例
Object singletonObject = this.singletonObjects.get(beanName);
//isSingletonCurrentlyInCreation=true,代表beanName所代表的bean循环依赖了
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//第二级缓存,保存的是未初始化完全的单例(只是实例化)
singletonObject = this.earlySingletonObjects.get(beanName);
//allowEarlyReference在当前场景下,默认为true
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);
}
在我们实例化bean之后,会把获取当前bean的方式放入到三级缓存
//AbstractAutowireCapableBeanFactory#doCreateBean
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);
}
});
}
具体三级缓存构造二级缓存的逻辑如下
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//这边可能返回的exposedObject可能不是之前的bean了,生成代理时目前的应用场景
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
if (exposedObject == null) {
return null;
}
}
}
}
return exposedObject;
}
在返回bean前,可能会通过SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference处理一下bean,返回修改后的exposedObject。
这边是重点?用于解答为啥不是二级缓存而是三级缓存。
因为SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference的实现为AbstractAutoProxyCreator
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
//幂等,防止重复生成代理
if (!this.earlyProxyReferences.contains(cacheKey)) {
this.earlyProxyReferences.add(cacheKey);
}
return wrapIfNecessary(bean, beanName, cacheKey);
}
上面的代码用于提前对bean生成代理。
按照正常的依赖注入,注入的bean,如果被切面切了,会通过postProcessAfterInitialization转换为代理对象。而对于循环依赖,会把未初始化完全的bean提前注入,但是可能bean可能是被切面切中的,所以使用第三级缓存中的getEarlyBeanReference发挥作用了,用于提前对未初始化的bean生成代理。
这边有个问题,提前对未初始化的bean生成代理,会不会影响该bean的正常初始化?
不会。代理对象引用了我们目标bean,目标bean的引用也还是被doCreateBean方法持有的。所以目标bean的初始化还是照常进行。
那么目标bean在执行到postProcessAfterInitialization钩子的时候,会不会重复生成代理?
不会,AbstractAutoProxyCreator#getEarlyBeanReference中使用earlyProxyReferences做了幂等。
在doGetBean中一直有段代码看不懂它的意图,现在也找到答案了
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
//用于将普通bean替换为它的代理对象
exposedObject = earlySingletonReference;
}
//走到这里说明有其他钩子把bean替换了,所以要检查在此之前是否已经发生过该bean的依赖注入,如果发生,就导致一个bean的不同版本被注入,针对这种情况,会抛出异常
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
善始善终,当循环依赖的bean构造好之后,他们的本体bean应该被放到一级缓存中,用于被其他bean获取。
//DefaultSingletonBeanRegistry#getSingleton#addSingleton
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}