spring 如何解決循環(huán)依賴
首先解釋下什么是循環(huán)依賴,其實很簡單,就是有兩個類它們互相都依賴了對方,如下所示:
@Componentpublic class AService { @Autowired private BService bService;}
@Componentpublic class BService { @Autowired private AService aService;}
AService和BService顯然兩者都在內(nèi)部依賴了對方,單拎出來看仿佛看到了多線程中常見的死鎖代碼,但很顯然Spring解決了這個問題,不然我們也不可能正常的使用它了。
所謂創(chuàng)建Bean實際上就是調(diào)用getBean() 方法,這個方法可以在AbstractBeanFactory這個類里面找到,這個方法一開始會調(diào)用getSingleton()方法。
// Eagerly check singleton cache for manually registered singletons.Object sharedInstance = getSingleton(beanName);
這個方法的實現(xiàn)長得很有意思,有著一堆if語句。
protected Object getSingleton(String beanName, boolean allowEarlyReference) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { synchronized(this.singletonObjects) {singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null) { ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); // 從三級緩存里取出放到二級緩存中 this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } }} } } } return singletonObject;}
但這一坨if很好理解,就是一層層的去獲取這個bean,首先從singletonObjects中獲取,這里面存放的是已經(jīng)完全創(chuàng)建好的單例Bean;如果取不到,那么就往下走,去earlySingletonObjects里面取,這個是早期曝光的對象;如果還是沒有,那么再去第三級緩存singletonFactories里面獲取,它是提前暴露的對象工廠,這里會從三級緩存里取出后放到二級緩存中。那么總的來說,Spring去獲取一個bean的時候,其實并不是直接就從容器里面取,而是先從緩存里找,而且緩存一共有三級。那么從這個方法返回的并不一定是我們需要的bean,后面會調(diào)用getObjectForBeanInstance()方法去得到實例化后的bean,這里就不多說了。
但如果緩存里面的確是取不到bean呢?那么說明這個bean的確還未創(chuàng)建,需要去創(chuàng)建一個bean,這樣我們就會去到前一篇生命周期中的創(chuàng)建bean的方法了。回顧下流程:實例化?屬性注入?初始化?銷毀。那么我們回到文章開頭的例子,有ServiceA和ServiceB兩個類。一般來說,Spring是按照自然順序去創(chuàng)建bean,那么第一個要創(chuàng)建的是ServiceA。顯然一開始緩存里是沒有的,我們會來到創(chuàng)建bean的方法。首先進行實例化階段,我們會來到第一個跟解決循環(huán)依賴有關(guān)的代碼,在實例化階段的代碼中就可以找到。
// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace('Eagerly caching bean ’' + beanName + '’ to allow for resolving potential circular references'); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}
首先看看第一行,earlySingletonExposure這個變量它會是什么值?
它是有一個條件表達式返回的,一個個來看,首先,mbd.isSingleton()。我們知道Spring默認的Bean的作用域都是單例的,因此這里正常來說都是返回true沒問題。第二個,this.allowCircularReference,這個變量是標記是否允許循環(huán)引用,默認也是true。第三個,調(diào)用了一個方法,isSingletonCurrentlyInCreation(beanName),進入該代碼可以看出它是返回當(dāng)前的bean是不是正常創(chuàng)建,顯然也是true。因此這個earlySingletonExposure返回的就是true。
接下來就進入了if語句的實現(xiàn)里面了,也就是addSingletonFactory()這個方法。看到里面的代碼中出現(xiàn)singletonFactories這個變量是不是很熟悉?翻到上面的getSingleton()就知道了,其實就是三級緩存,所以這個方法的作用是通過三級緩存提前暴露一個工廠對象。
/** * Add the given singleton factory for building the specified singleton * if necessary. * <p>To be called for eager registration of singletons, e.g. to be able to * resolve circular references. * @param beanName the name of the bean * @param singletonFactory the factory for the singleton object */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); this.registeredSingletons.add(beanName); } }}
接下來,回憶下上一章節(jié)說的實例化之后的步驟,就是屬性注入了。這就意味著ServiceA需要將ServiceB注入進去,那么顯然又要調(diào)用getBean()方法去獲取ServiceB。ServiceB還沒有創(chuàng)建,則也會進入這個createBean()方法,同樣也會來到這一步依賴注入。ServiceB中依賴了ServiceA,則會調(diào)用getBean()去獲取ServiceA。此時的獲取ServiceA可就不是再創(chuàng)建Bean了,而是從緩存中獲取。這個緩存就是上面getSingleton()這個方法里面我們看到的singletonFactory。那么這個singletonFactory哪里來的,就是這個addSingletonFactory()方法的第二個參數(shù),即getEarlyBeanReference()方法。
/** * Obtain a reference for early access to the specified bean, * typically for the purpose of resolving a circular reference. * @param beanName the name of the bean (for error handling purposes) * @param mbd the merged bean definition for the bean * @param bean the raw bean instance * @return the object to expose as bean reference */protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) { exposedObject = bp.getEarlyBeanReference(exposedObject, beanName); } } return exposedObject;}
查看bp.getEarlyBeanReference(exposedObject, beanName)的實現(xiàn),發(fā)現(xiàn)有兩個,一個是spring-beans下的SmartInstantiationAwareBeanPostProcessor,一個是spring-aop下的AbstractAutoProxyCreator。我們在未使用AOP的情況下,取的還是第一種實現(xiàn)。
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { return bean;}
那么令人驚訝的是,這方法直接返回了bean,也就是說如果不考慮AOP的話,這個方法啥都沒干,就是把實例化創(chuàng)建的對象直接返回了。如果考慮AOP的話調(diào)用的是另一個實現(xiàn):
public Object getEarlyBeanReference(Object bean, String beanName) { Object cacheKey = getCacheKey(bean.getClass(), beanName); this.earlyProxyReferences.put(cacheKey, bean); return wrapIfNecessary(bean, beanName, cacheKey);}
可以看出,如果使用了AOP的話,這個方法返回的實際上是bean的代理,并不是它本身。那么通過這部分我們可以認為,在沒有使用AOP的情況下,三級緩存是沒有什么用的,所謂三級緩存實際上只是跟Spring的AOP有關(guān)的。
好了我們現(xiàn)在是處于創(chuàng)建B的過程,但由于B依賴A,所以調(diào)用了獲取A的方法,則A從三級緩存進入了二級緩存,得到了A的代理對象。當(dāng)然我們不需要擔(dān)心注入B的是A的代理對象會帶來什么問題,因為生成代理類的內(nèi)部都是持有一個目標類的引用,當(dāng)調(diào)用代理對象的方法的時候,實際上是會調(diào)用目標對象的方法的,所以所以代理對象是沒影響的。當(dāng)然這里也反應(yīng)了我們實際上從容器中要獲取的對象實際上是代理對象而不是其本身。
那么我們再回到創(chuàng)建A的邏輯往下走,能看到后面實際上又調(diào)用了一次getSingleton()方法。傳入的allowEarlyReference為false。
if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } ... }}
翻看上面的getSingleton()代碼可以看出,allowEarlyReference為false就相當(dāng)于禁用三級緩存,代碼只會執(zhí)行到通過二級緩存get。
singletonObject = this.earlySingletonObjects.get(beanName);
因為在前面我們在創(chuàng)建往B中注入A的時候已經(jīng)從三級緩存取出來放到二級緩存中了,所以這里A可以通過二級緩存去取。再往下就是生命周期后面的代碼了,就不再繼續(xù)了。
那么現(xiàn)在就會有個疑問,我們?yōu)槭裁捶且壘彺妫苯佑枚壘彺嫠坪蹙妥銐蛄耍?/p>
看看上面getEarlyBeanReference()這個方法所在的類,它是SpringAOP自動代理的關(guān)鍵類,它實現(xiàn)了SmartInstantiationAwareBeanPostProcessor,也就是說它也是個后置處理器BeanPostProcessor,它有著自定義的初始化后的方法。
/** * Create a proxy with the configured interceptors if the bean is * identified as one to proxy by the subclass. * @see #getAdvicesAndAdvisorsForBean */@Overridepublic Object postProcessAfterInitialization(@Nullable Object bean, String beanName) { if (bean != null) { Object cacheKey = getCacheKey(bean.getClass(), beanName); if (this.earlyProxyReferences.remove(cacheKey) != bean) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean;}
很明顯它這里是earlyProxyReferences緩存中找不到當(dāng)前的bean的話就會去創(chuàng)建代理。也就是說SpringAOP希望在Bean初始化后進行創(chuàng)建代理。如果我們只使用二級緩存,也就是在這個地方
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
直接調(diào)用getEarlyBeanReference()并將得到的早期引用放入二級緩存。這就意味著無論bean之間是否存在互相依賴,只要創(chuàng)建bean走到這一步都得去創(chuàng)建代理對象了。然而Spring并不想這么做,不信自己可以動手debug一下,如果ServiceA和ServiceB之間沒有依賴關(guān)系的話,getEarlyBeanReference()這個方法壓根就不會執(zhí)行。總的來說就是,如果不使用三級緩存直接使用二級緩存的話,會導(dǎo)致所有的Bean在實例化后就要完成AOP代理,這是沒有必要的。
最后我們重新梳理下流程,記得Spring創(chuàng)建Bean的時候是按照自然順序的,所以A在前B在后:
我們首先進行A的創(chuàng)建,但由于依賴了B,所以開始創(chuàng)建B,同樣的,對B進行屬性注入的時候會要用到A,那么就會通過getBean()去獲取A,A在實例化階段會提前將對象放入三級緩存中,如果沒有使用AOP,那么本質(zhì)上就是這個bean本身,否則是AOP代理后的代理對象。三級緩存singletonFactories會將其存放進去。那么通過getBean()方法獲取A的時候,核心其實在于getSingleton()方法, 它會將其從三級緩存中取出,然后放到二級緩存中去。而最終B創(chuàng)建結(jié)束回到A初始化的時候,會再次調(diào)用一次getSingleton()方法,此時入?yún)⒌腶llowEarlyReference為false,因此是去二級緩存中取,得到真正需要的bean或代理對象,最后A創(chuàng)建結(jié)束,流程結(jié)束。
所以Spring解決循環(huán)依賴的原理大致就講完了,但根據(jù)上述的結(jié)論,我們可以思考一個問題,什么情況的循環(huán)依賴是無法解決的?
根據(jù)上面的流程圖,我們知道,要解決循環(huán)依賴首先一個大前提是bean必須是單例的,基于這個前提我們才值得繼續(xù)討論這個問題。然后根據(jù)上述總結(jié),可以知道,每個bean都是要進行實例化的,也就是要執(zhí)行構(gòu)造器。所以能不能解決循環(huán)依賴問題其實跟依賴注入的方式有關(guān)。
依賴注入的方式有setter注入,構(gòu)造器注入和Field方式。
Filed方式就是我們平時用的最多的,屬性上加個@Autowired或者@Resource之類的注解,這個對解決循環(huán)依賴無影響;
如果A和B都是通過setter注入,顯然對于執(zhí)行構(gòu)造器沒有影響,所以不影響解決循環(huán)依賴;
如果A和B互相通過構(gòu)造器注入,那么執(zhí)行構(gòu)造器的時候也就是實例化的時候,A在自己還沒放入緩存的時候就去創(chuàng)建B了,那么B也是拿不到A的,因此會出錯;
如果A中注入B的方式為setter,B中注入A為構(gòu)造器,由于A先實例化,執(zhí)行構(gòu)造器,并創(chuàng)建緩存,都沒有問題,繼續(xù)屬性注入,依賴了B然后走創(chuàng)建B的流程,獲取A也可以從緩存里面能取到,流程一路通暢。
如果A中注入B的方式為構(gòu)造器,B中注入A為setter,那么這個時候A先進入實例化方法,發(fā)現(xiàn)需要B,那么就會去創(chuàng)建B,而A還沒放入三級緩存里,B再創(chuàng)建的時候去獲取A就會獲取失敗。
好了,以上就是關(guān)于Spring解決循環(huán)依賴問題的所有內(nèi)容,這個問題的答案我是很久之前就知道了,但真的只是知道答案,這次是自己看源碼加debug一點點看才知道為啥是這個答案,雖然還做不到徹底學(xué)的通透,但的確能對這個問題的理解的更為深刻一點,再接再厲吧。
以上就是spring 如何解決循環(huán)依賴的詳細內(nèi)容,更多關(guān)于spring 循環(huán)依賴的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. idea修改背景顏色樣式的方法2. jsp EL表達式詳解3. asp知識整理筆記4(問答模式)4. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實現(xiàn)5. 解決ajax的delete、put方法接收不到參數(shù)的問題方法6. chat.asp聊天程序的編寫方法7. Django ORM實現(xiàn)按天獲取數(shù)據(jù)去重求和例子8. XML入門的常見問題(一)9. Jsp中request的3個基礎(chǔ)實踐10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
