Spring解決循環(huán)依賴源碼分析

本文基于spring4.3.9

什么是循環(huán)依賴

在spring中一個(gè)bean依賴另外一個(gè)bean有兩種方式,一是通過構(gòu)造函數(shù),二是通過字段注入。
用代碼來解釋循環(huán)依賴,那么就是以下場景

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;  
}

如何解決

循環(huán)依賴只存在于singleton類型bean之間

對于構(gòu)造函數(shù)循環(huán)依賴的情況,spring無能為力,在獲取bean前spring中會(huì)通過下面代碼拋出異常

    protected void beforeSingletonCreation(String beanName) {
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
    }

singletonsCurrentlyInCreation會(huì)保存當(dāng)前正在構(gòu)造中的beanName,錯(cuò)誤產(chǎn)生邏輯大概如下:

  1. 我們向BeanFactory獲取A類型的bean
  2. A類型bean準(zhǔn)備構(gòu)造,把beanName保存到singletonsCurrentlyInCreation
  3. A類型通過構(gòu)造函數(shù)實(shí)例化,依賴B類型的Bean,向BeanFactory請求B類型Bean
  4. B類型bean準(zhǔn)備構(gòu)造,把beanName保存到singletonsCurrentlyInCreation
  5. B類型通過構(gòu)造函數(shù)實(shí)例化,依賴A類型的Bean,向BeanFactory請求A類型Bean
  6. 在DefaultSingletonBeanRegistry#getSingleton#beforeSingletonCreation方法的檢查singletonsCurrentlyInCreation是否已經(jīng)包含當(dāng)前請求的beanName,拋出異常

而對于字段注入類型或者字段注入和構(gòu)造函數(shù)混合的循環(huán)依賴,spring通過緩存解決這個(gè)問題。因?yàn)槠渲幸粋€(gè)對象是可實(shí)例化的!!

我們以字段注入類型的循環(huán)依賴為例

  1. 我們向BeanFactory獲取A類型的bean
  2. A類型bean實(shí)例化,把未初始化的自己放到緩存中
  3. A類型bean進(jìn)行構(gòu)造(populdateBean),觸發(fā)了依賴注入B
  4. 我們向BeanFactory獲取B類型的bean
  5. B類型bean實(shí)例化,把未初始化的自己放到緩存中
  6. B類型bean進(jìn)行構(gòu)造(populdateBean),觸發(fā)了依賴注入A
  7. 從二級(jí)緩存中獲取到未初始化的A
  8. B類型bean進(jìn)行初始化,返回給第3步的A進(jìn)行依賴注入
  9. A類型bean進(jìn)行初始化
  10. 返回給調(diào)用getBean的方法

這個(gè)緩存我們稱它為三級(jí)緩存,它的代碼如下,會(huì)在doGetBean的開頭被調(diào)用

//DefaultSingletonBeanRegistry#getSingleton
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //singletonObjects 第一級(jí)緩存,BeanFactory的單例全存在singletonObjects中
    //保存的是已經(jīng)初始化完全的單例
    Object singletonObject = this.singletonObjects.get(beanName);
            //isSingletonCurrentlyInCreation=true,代表beanName所代表的bean循環(huán)依賴了
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        synchronized (this.singletonObjects) {
            //第二級(jí)緩存,保存的是未初始化完全的單例(只是實(shí)例化)
            singletonObject = this.earlySingletonObjects.get(beanName);
            //allowEarlyReference在當(dāng)前場景下,默認(rèn)為true
            if (singletonObject == null && allowEarlyReference) {
                //第三級(jí)緩存,不是真的緩存,緩存的是生成二級(jí)緩存的工廠方法
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                    //通過三級(jí)緩存構(gòu)造二級(jí)緩存
                    singletonObject = singletonFactory.getObject();
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

在我們實(shí)例化bean之后,會(huì)把獲取當(dāng)前bean的方式放入到三級(jí)緩存

//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");
    }
    //添加三級(jí)緩存
    addSingletonFactory(beanName, new ObjectFactory<Object>() {
        @Override
        public Object getObject() throws BeansException {
            return getEarlyBeanReference(beanName, mbd, bean);
        }
    });
}

具體三級(jí)緩存構(gòu)造二級(jí)緩存的邏輯如下

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了,生成代理時(shí)目前的應(yīng)用場景
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return null;
                }
            }
        }
    }
    return exposedObject;
}

在返回bean前,可能會(huì)通過SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference處理一下bean,返回修改后的exposedObject。

這邊是重點(diǎn)?用于解答為啥不是二級(jí)緩存而是三級(jí)緩存。

因?yàn)镾martInstantiationAwareBeanPostProcessor#getEarlyBeanReference的實(shí)現(xiàn)為AbstractAutoProxyCreator

public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
    Object cacheKey = getCacheKey(bean.getClass(), beanName);
    //冪等,防止重復(fù)生成代理
    if (!this.earlyProxyReferences.contains(cacheKey)) {
        this.earlyProxyReferences.add(cacheKey);
    }
    return wrapIfNecessary(bean, beanName, cacheKey);
}

上面的代碼用于提前對bean生成代理。

按照正常的依賴注入,注入的bean,如果被切面切了,會(huì)通過postProcessAfterInitialization轉(zhuǎn)換為代理對象。而對于循環(huán)依賴,會(huì)把未初始化完全的bean提前注入,但是可能bean可能是被切面切中的,所以使用第三級(jí)緩存中的getEarlyBeanReference發(fā)揮作用了,用于提前對未初始化的bean生成代理。

這邊有個(gè)問題,提前對未初始化的bean生成代理,會(huì)不會(huì)影響該bean的正常初始化?

不會(huì)。代理對象引用了我們目標(biāo)bean,目標(biāo)bean的引用也還是被doCreateBean方法持有的。所以目標(biāo)bean的初始化還是照常進(jìn)行。

那么目標(biāo)bean在執(zhí)行到postProcessAfterInitialization鉤子的時(shí)候,會(huì)不會(huì)重復(fù)生成代理?

不會(huì),AbstractAutoProxyCreator#getEarlyBeanReference中使用earlyProxyReferences做了冪等。

在doGetBean中一直有段代碼看不懂它的意圖,現(xiàn)在也找到答案了

if (earlySingletonExposure) {
    Object earlySingletonReference = getSingleton(beanName, false);
    if (earlySingletonReference != null) {
        if (exposedObject == bean) {
            //用于將普通bean替換為它的代理對象
            exposedObject = earlySingletonReference;
        }
        //走到這里說明有其他鉤子把bean替換了,所以要檢查在此之前是否已經(jīng)發(fā)生過該bean的依賴注入,如果發(fā)生,就導(dǎo)致一個(gè)bean的不同版本被注入,針對這種情況,會(huì)拋出異常
        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.");
            }
        }
    }
}

善始善終,當(dāng)循環(huán)依賴的bean構(gòu)造好之后,他們的本體bean應(yīng)該被放到一級(jí)緩存中,用于被其他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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容