springboot bean循環依賴實現以及源碼分析
前言
本文基於springboot版本2.5.1
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.1</version> <relativePath/> <!-- lookup parent from repository --> </parent>
本文主要聚焦在循環依賴部分,主要用單例bean來進行講解,其他bean實現的流程不會過多涉及。
1、什麼叫循環依賴呢
簡單來說就是springboot容器中的多個bean,如A、B兩個bean,A有屬性B需要註入,B有屬性A需要註入,形成相互依賴的情況。
看下代碼,就是類似下面這種情況
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ServiceA { @Autowired private ServiceB serviceB; }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ServiceB { @Autowired private ServiceA serviceA; }
上面有兩個bean,分別是ServiceA,ServiceB。ServiceA中需要註入ServiceB的實例,ServiceB中需要註入ServiceA的實例,這就是一種典型的循環依賴,其他還有方法參數循環依賴的場景等等,但是它們的內部實現基本是一樣的。
2、具體出現循環依賴的代碼邏輯
獲取bean的方法
在springboot中默認的beanFactory是DefaultListableBeanFactory,在我們獲取bean對象的時候,如果bean對象存在就直接返回,如果不存在,就先創建bean對象再返回。
我們先看下我們獲取bean的常用方法都有哪些
public <T> T getBean(Class<T> requiredType) throws BeansException public Object getBean(String name) throws BeansException public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) public void preInstantiateSingletons() throws BeansException
常用的獲取bean的方法主要有上面幾個和它們的重載版本,對於第3行、第4行、第5行最終都會調用到第2行的方法來獲取bean。而它也會通過調用doGetBean(在AbstractBeanFactory這個類中)來獲取bean
public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
第1行的方法也會調用doGetBean來獲取bean
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); }
所有最終獲取bean的方法都是
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
這個方法,這個方法是protected的,是不對外提供的。所以我們不能直接調用它,隻能通過上面提供的5個方法來獲取bean對象。
下面我們從doGetBean這裡來看下serviceA創建的過程
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { //如果bean之前存在,這裡返回的shareInstance就是非空,就會從後面的if分支中返回,如果bean之前不存在,就會執行後面的bean創建及註入屬性的過程 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { ...... //如果當前不隻是檢查,而且是創建bean,這個參數就是false,在這裡就會做個bean創建的標記,把beanName 加到alreadyCreated裡面去 if (!typeCheckOnly) { markBeanAsCreated(beanName); } //我們當前要創建的bean是單例的,就會走到這裡去,下面我們走到裡面的調用去看看 // Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } }
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { ...... //這裡會把當前bean的名字加入到當前正在創建的單例對象集合singletonsCurrentlyInCreation中 beforeSingletonCreation(beanName); ...... try { //這裡就是調用上面的return createBean(beanName, mbd, args);這個方法,我們進這裡面去看看 singletonObject = singletonFactory.getObject(); newSingleton = true; } ...... } return singletonObject; } }
@Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { ...... // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. //在這裡獲取要創建的bean的class對象 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); ...... try { //調用這裡來創建,我們再走到這裡面去看看 //3個參數分別為 //1、beanName bean對象的名字 //2、mbdToUseRootBeanDefinition對象,可以認為就是bean的元數據信息,包含bean的類對象,bean的類上註解,bean實際位置路徑等等 //3、args bean對象的構造方法的實參,這裡一般是空的 Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } ...... }
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { ...... //真正創建bean對象是在這裡,這裡返回的instanceWrapper是bean對象的類實例的包裝對象BeanWrapper if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } //這裡的bean就是實際創建的bean對象的類實例 Object bean = instanceWrapper.getWrappedInstance(); Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } ...... // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. //看上面的註釋大概也能明白, 大概意思就是早期的單例緩存,為瞭解決由 BeanFactoryAware等等觸發的循環依賴 //mbd.isSingleton() 表示bean是單例的(這個是bean對應的類上的,默認就是單例), //this.allowCircularReferences 允許循環引用,這個是beanFactory的成員屬性,默認也是true //isSingletonCurrentlyInCreation(beanName) 表示是否在當前正在創建的bean集合中。beforeSingletonCreation(beanName);我們在前面執行過這句就加到正在創建的bean集合中瞭 //這裡earlySingletonExposure 就是true瞭,會進到if分支中 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"); } //這句主要是將將() -> getEarlyBeanReference(beanName, mbd, bean) 這個lambda表達式存儲到this.singletonFactories集合中 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; try { //在這裡就會進行屬性填充,完成成員註入等等,也就是在這裡serviceA這個bean會註入serviceB這個成員屬性,我們走進這個方法去看看 populateBean(beanName, mbd, instanceWrapper); ...... } ...... return exposedObject; }
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { ...... if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } //真正的屬性註入是在這裡完成的,aop也是在這裡來完成的。這裡是獲取beanFactory中的InstantiationAwareBeanPostProcessor對bean對象進行增強 //如果屬性註入用的是@Resource,就會用CommonAnnotationBeanPostProcessor來完成 //如果屬性註入用的是@Autowired,就會用AutowiredAnnotationBeanPostProcessor來完成 //如果是AOP 就會使用InfrastructureAdvisorAutoProxyCreator來生成對應的代理對象 //我們這裡使用的是@Autowired,所以會用AutowiredAnnotationBeanPostProcessor來完成註入。我們走到它的postProcessProperties的去看看 for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) { PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); ...... }
@Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { //這裡主要是獲取bean的類屬性和方法上的org.springframework.beans.factory.annotation.Autowired,org.springframework.beans.factory.annotation.Value註解來進行註入 InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { //繼續進去看看 metadata.inject(bean, beanName, pvs); } ...... }
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { ...... //對每一個屬性分別進行註入,繼續進去 element.inject(target, beanName, pvs); } } }
@Override protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Field field = (Field) this.member; Object value; //如果之前緩存過就從緩存取,我們是第一次註入,所以之前沒有緩存,不會走這個分支 if (this.cached) { try { value = resolvedCachedArgument(beanName, this.cachedFieldValue); } catch (NoSuchBeanDefinitionException ex) { // Unexpected removal of target bean for cached argument -> re-resolve value = resolveFieldValue(field, bean, beanName); } } else { //會走這裡來解析字段的值,再進去 value = resolveFieldValue(field, bean, beanName); } if (value != null) { ReflectionUtils.makeAccessible(field); field.set(bean, value); } }
@Nullable private Object resolveFieldValue(Field field, Object bean, @Nullable String beanName) { //創建字段的包裝類DependencyDescriptor DependencyDescriptor desc = new DependencyDescriptor(field, this.required); try { //調用這裡完成對應字段值的查找,再進去 value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } synchronized (this) { //獲取到值之後,進行緩存 if (!this.cached) { ...... } this.cachedFieldValue = cachedFieldValue; this.cached = true; } } return value; } }
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { //當前的類是一個普通的class,會走到這裡面,由於我們的bean沒有Lazy註解,所以這裡返回時null,走到下面的if分支 Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { //在這裡我們看下這裡的入參。 //descriptor是包含瞭需要註入的字段的信息。 //requestingBeanName是當前正在創建的bean的名字serviceA, //autowiredBeanNames是當前需要註入的字段的對應的bean的名字的集合,這裡隻有serviceB //typeConverter這個是進行註入時做類型轉換的,這裡我們可以不用關註這個 result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } }
@Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { ...... if (instanceCandidate instanceof Class) { //又會調用到這裡,我們再進入到DependencyDescriptor的resolveCandidate去看看 //註意:這裡的autowiredBeanName是我們需要註入的屬性名這裡是serviceB instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } ...... }
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) throws BeansException { //看到沒,到這裡就出現循環調用瞭,到這裡又會重新調用beanFactory.getBean("serviceB")去創建serviceB的bean對象,完成後註入到serivceA對應的Bean上的屬性上來,這時代碼又會從本節開頭的位置開始執行,先創建serviceB對象實例,再去註入serviceB對象的serviceA屬性。 //最終會執行到beanFactory.getBean("serviceA")這裡 return beanFactory.getBean(beanName); }
就是下面圖的樣子
3、解決循環依賴的代碼實現
接著上面的beanFactory.getBean(“serviceA”)這行代碼我們繼續往下看
這次又會走到這裡
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { //我們第二部分就是從這裡開始的,又走回來瞭,但這次又會有所不同 String beanName = transformedBeanName(name); Object beanInstance; // Eagerly check singleton cache for manually registered singletons. //這次我們這裡返回的就不是空瞭,sharedInstance對象的值就是對應serviceA的bean對象瞭,這次就會從if分支中返回,而之前我們不會進這裡的if分支而是進入else分支導致後面出現瞭循環依賴的問題,這次我們進到這個方法看看 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null); }
@Nullable public Object getSingleton(String beanName) { //再點進去 return getSingleton(beanName, true); }
protected Object getSingleton(String beanName, boolean allowEarlyReference) { // Quick check for existing instance without full singleton lock Object singletonObject = this.singletonObjects.get(beanName); //這裡由於當前的serviceA bean還沒完成創建,所以這裡singletonObject返回的是空, //再看看 isSingletonCurrentlyInCreation(beanName)這裡,由於我們在創建serviceA過程中有這麼一句beforeSingletonCreation(beanName)(不清楚這句的搜索下本文,上面就有講到),所有這個條件是true。這時我們就會進入if分支中 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { singletonObject = this.earlySingletonObjects.get(beanName); //由於我們是第一次進入這裡,所以this.earlySingletonObjects.get(beanName)返回的也是null //我們的入參 allowEarlyReference是true,會繼續進到這個if分支中 if (singletonObject == null && allowEarlyReference) { synchronized (this.singletonObjects) { // Consistent creation of early reference within full singleton lock singletonObject = this.singletonObjects.get(beanName); //這裡的singletonObject還是null,繼續進到if分支 if (singletonObject == null) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null) { //最終會走到這裡,在創建serviceA對象之後,屬性註入之前,執行瞭這句 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))(不清楚的搜索下本文,上面有說到),所以這裡返回的singletonFactory是個lamdba表達式,getEarlyBeanReference(beanName, mbd, bean))附帶瞭3個參數,第一個beanName是serivceA,mdb是對應serviceA的附帶serviceA元數據信息的RootBeanDefinition對象,bean就是創建出來的serviceA對象 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { //這裡就會調用getEarlyBeanReference(beanName, mbd, bean)對serviceA對象進行一個getEarlyBeanReference增強後返回,返回後放置到earlySingletonObjects中,並從singletonFactories中刪除 singletonObject = singletonFactory.getObject(); this.earlySingletonObjects中,並從.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } } } return singletonObject; }
最終在serviceA 這個bean創建完成後,就會從singletonsCurrentlyInCreation移除掉
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { ...... finally { //在這裡從singletonsCurrentlyInCreation中移除掉 afterSingletonCreation(beanName); } if (newSingleton) { //將serviceA bean對象添加到singletonObjects,registeredSingletons中 //從singletonFactories,earlySingletonObjects中移除掉 addSingleton(beanName, singletonObject); } } return singletonObject; } }
所以整個獲取serviceA的流程就是這樣瞭,
1、首先去創建serviceA這個bean,
- 由於它有個屬性serviceB,在創建完serviceA對象後,就會去進行serviceB的屬性註入,
- 這時由於serviceB之前沒有生成,這時又會去創建serviceB這個bean,
- 先創建serviceB對象,然後再進行serviceA這個屬性的註入,
- 繼續去獲取serviceA這個bean,第二次進入獲取serviceA的流程,這時從之前緩存的lambda表達式中獲取到之前創建的serviceA的引用返回。
2、總結下關鍵的代碼點
- 創建bean對象之前調用beforeSingletonCreation(beanName)將bean對象名字添加到singletonsCurrentlyInCreation集合中
- 創建bean對象對應的類實例後調用addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));添加到singletonFactories中
- 在循環依賴中第二次調用到創建bean對象時,調用getSingleton(beanName, true)時,從singletonFactories中返回對應的早期bean對象的引用,並添加到earlySingletonObjects中
總結
到此這篇關於springboot bean循環依賴實現以及源碼分析的文章就介紹到這瞭,更多相關springboot bean循環依賴內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBean依賴和三級緩存的案例講解
- 關於spring循環依賴問題及解決方案
- Java中的Spring 如何處理循環依賴
- Spring源碼剖析之Spring處理循環依賴的問題
- 聊聊Spring循環依賴三級緩存是否可以減少為二級緩存的情況