最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Spring循環(huán)依賴的解決方案

 更新時間:2018年05月24日 11:01:00   作者:數(shù)齊  
這篇文章主要介紹了詳解Spring循環(huán)依賴的解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

spring針對Bean之間的循環(huán)依賴,有自己的處理方案。關(guān)鍵點就是三級緩存。當(dāng)然這種方案不能解決所有的問題,他只能解決Bean單例模式下非構(gòu)造函數(shù)的循環(huán)依賴。

我們就從A->B->C-A這個初始化順序,也就是A的Bean中需要B的實例,B的Bean中需要C的實例,C的Bean中需要A的實例,當(dāng)然這種需要不是構(gòu)造函數(shù)那種依賴。前提條件有了,我們就可以開始了。毫無疑問,我們會先初始化A.初始化的方法是org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

protected <T> T doGetBean(
   final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
   throws BeansException {

  final String beanName = transformedBeanName(name);
  Object bean;

  // Eagerly check singleton cache for manually registered singletons.
  Object sharedInstance = getSingleton(beanName); //關(guān)注點1
  if (sharedInstance != null && args == null) {
   if (logger.isDebugEnabled()) {
    if (isSingletonCurrentlyInCreation(beanName)) {
     logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
       "' that is not fully initialized yet - a consequence of a circular reference");
    }
    else {
     logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
    }
   }
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  }

  else {
   // Fail if we're already creating this bean instance:
   // We're assumably within a circular reference.
   if (isPrototypeCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(beanName);
   }

   // Check if bean definition exists in this factory.
   BeanFactory parentBeanFactory = getParentBeanFactory();
   if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    // Not found -> check parent.
    String nameToLookup = originalBeanName(name);
    if (args != null) {
     // Delegation to parent with explicit args.
     return (T) parentBeanFactory.getBean(nameToLookup, args);
    }
    else {
     // No args -> delegate to standard getBean method.
     return parentBeanFactory.getBean(nameToLookup, requiredType);
    }
   }

   if (!typeCheckOnly) {
    markBeanAsCreated(beanName);
   }

   try {
    final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    checkMergedBeanDefinition(mbd, beanName, args);

    // Guarantee initialization of beans that the current bean depends on.
    String[] dependsOn = mbd.getDependsOn();
    if (dependsOn != null) {
     for (String dependsOnBean : dependsOn) {
      if (isDependent(beanName, dependsOnBean)) {
       throw new BeanCreationException(mbd.getResourceDescription(), beanName,
         "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
      }
      registerDependentBean(dependsOnBean, beanName);
      getBean(dependsOnBean);
     }
    }

    // Create bean instance.
    if (mbd.isSingleton()) {
     //關(guān)注點2
     sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
      @Override
      public Object getObject() throws BeansException {
       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;
       }
      }
     });
     bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    }

    else if (mbd.isPrototype()) {
     // It's a prototype -> create a new instance.
     Object prototypeInstance = null;
     try {
      beforePrototypeCreation(beanName);
      prototypeInstance = createBean(beanName, mbd, args);
     }
     finally {
      afterPrototypeCreation(beanName);
     }
     bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
    }

    else {
     String scopeName = mbd.getScope();
     final Scope scope = this.scopes.get(scopeName);
     if (scope == null) {
      throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
     }
     try {
      Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
       @Override
       public Object getObject() throws BeansException {
        beforePrototypeCreation(beanName);
        try {
         return createBean(beanName, mbd, args);
        }
        finally {
         afterPrototypeCreation(beanName);
        }
       }
      });
      bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
     }
     catch (IllegalStateException ex) {
      throw new BeanCreationException(beanName,
        "Scope '" + scopeName + "' is not active for the current thread; consider " +
        "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
        ex);
     }
    }
   }
   catch (BeansException ex) {
    cleanupAfterBeanCreationFailure(beanName);
    throw ex;
   }
  }

  // Check if required type matches the type of the actual bean instance.
  if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
   try {
    return getTypeConverter().convertIfNecessary(bean, requiredType);
   }
   catch (TypeMismatchException ex) {
    if (logger.isDebugEnabled()) {
     logger.debug("Failed to convert bean '" + name + "' to required type [" +
       ClassUtils.getQualifiedName(requiredType) + "]", ex);
    }
    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
   }
  }
  return (T) bean;
 }

這個方法很長我們一點點說。先看我們的關(guān)注點1 Object sharedInstance = getSingleton(beanName)根據(jù)名稱從單例的集合中獲取單例對象,我們看下這個方法,他最終是org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)

 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 != NULL_OBJECT ? singletonObject : null);
 }

大家一定要注意這個方法,很關(guān)鍵,我們開篇提到了三級緩存,使用點之一就是這里。到底是哪三級緩存呢,第一級緩存singletonObjects里面放置的是實例化好的單例對象。第二級earlySingletonObjects里面存放的是提前曝光的單例對象(沒有完全裝配好)。第三級singletonFactories里面存放的是要被實例化的對象的對象工廠。解釋好了三級緩存,我們再看看邏輯。第一次進來this.singletonObjects.get(beanName)返回的肯定是null。然后isSingletonCurrentlyInCreation決定了能否進入二級緩存中獲取數(shù)據(jù)。

public boolean isSingletonCurrentlyInCreation(String beanName) {
  return this.singletonsCurrentlyInCreation.contains(beanName);
 }

singletonsCurrentlyInCreation這個Set中有沒有包含傳入的BeanName,前面沒有地方設(shè)置,所以肯定不包含,所以這個方法返回false,后面的流程就不走了。getSingleton這個方法返回的是null。

下面我們看下關(guān)注點2.也是一個getSingleton只不過他是真實的創(chuàng)建Bean的過程,我們可以看到傳入了一個匿名的ObjectFactory的對象,他的getObject方法中調(diào)用的是createBean這個真正的創(chuàng)建Bean的方法。當(dāng)然我們可以先擱置一下,繼續(xù)看我們的getSingleton方法

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  Assert.notNull(beanName, "'beanName' must not be null");
  synchronized (this.singletonObjects) {
   Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null) {
    if (this.singletonsCurrentlyInDestruction) {
     throw new BeanCreationNotAllowedException(beanName,
       "Singleton bean creation not allowed while the singletons of this factory are in destruction " +
       "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
    }
    if (logger.isDebugEnabled()) {
     logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
    }
    beforeSingletonCreation(beanName);
    boolean newSingleton = false;
    boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
    if (recordSuppressedExceptions) {
     this.suppressedExceptions = new LinkedHashSet<Exception>();
    }
    try {
     singletonObject = singletonFactory.getObject();
     newSingleton = true;
    }
    catch (IllegalStateException ex) {
     // Has the singleton object implicitly appeared in the meantime ->
     // if yes, proceed with it since the exception indicates that state.
     singletonObject = this.singletonObjects.get(beanName);
     if (singletonObject == null) {
      throw ex;
     }
    }
    catch (BeanCreationException ex) {
     if (recordSuppressedExceptions) {
      for (Exception suppressedException : this.suppressedExceptions) {
       ex.addRelatedCause(suppressedException);
      }
     }
     throw ex;
    }
    finally {
     if (recordSuppressedExceptions) {
      this.suppressedExceptions = null;
     }
     afterSingletonCreation(beanName);
    }
    if (newSingleton) {
     addSingleton(beanName, singletonObject);
    }
   }
   return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }
 }

這個方法的第一句Object singletonObject = this.singletonObjects.get(beanName)從一級緩存中取數(shù)據(jù),肯定是null。隨后就調(diào)用的beforeSingletonCreation方法。

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

其中就有往singletonsCurrentlyInCreation這個Set中添加beanName的過程,這個Set很重要,后面會用到。隨后就是調(diào)用singletonFactory的getObject方法進行真正的創(chuàng)建過程,下面我們看下剛剛上文提到的真正的創(chuàng)建的過程createBean,它里面的核心邏輯是doCreateBean.

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
  // Instantiate the bean.
  BeanWrapper instanceWrapper = null;
  if (mbd.isSingleton()) {
   instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  }
  if (instanceWrapper == null) {
   instanceWrapper = createBeanInstance(beanName, mbd, args);
  }
  final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
  Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

  // Allow post-processors to modify the merged bean definition.
  synchronized (mbd.postProcessingLock) {
   if (!mbd.postProcessed) {
    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
    mbd.postProcessed = true;
   }
  }

  // Eagerly cache singletons to be able to resolve circular references
  // even when triggered by lifecycle interfaces like BeanFactoryAware.
  //關(guān)注點3
  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);
    }
   });
  }

  // Initialize the bean instance.
  Object exposedObject = bean;
  try {
   populateBean(beanName, mbd, instanceWrapper);
   if (exposedObject != null) {
    exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
  }
  catch (Throwable ex) {
   if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
    throw (BeanCreationException) ex;
   }
   else {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
   }
  }

  if (earlySingletonExposure) {
   Object earlySingletonReference = getSingleton(beanName, false);
   if (earlySingletonReference != null) {
    if (exposedObject == bean) {
     exposedObject = earlySingletonReference;
    }
    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.");
     }
    }
   }
  }

  // Register bean as disposable.
  try {
   registerDisposableBeanIfNecessary(beanName, bean, mbd);
  }
  catch (BeanDefinitionValidationException ex) {
   throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  }

  return exposedObject;
 }

createBeanInstance利用反射創(chuàng)建了對象,下面我們看看關(guān)注點3 earlySingletonExposure屬性值的判斷,其中有一個判斷點就是isSingletonCurrentlyInCreation(beanName)

public boolean isSingletonCurrentlyInCreation(String beanName) {
  return this.singletonsCurrentlyInCreation.contains(beanName);
 }

發(fā)現(xiàn)使用的是singletonsCurrentlyInCreation這個Set,上文的步驟中已經(jīng)將BeanName已經(jīng)填充進去了,所以可以查到,所以earlySingletonExposure這個屬性是結(jié)合其他的條件綜合判斷為true,進行下面的流程addSingletonFactory,這里是為這個Bean添加ObjectFactory,這個BeanName(A)對應(yīng)的對象工廠,他的getObject方法的實現(xiàn)是通過getEarlyBeanReference這個方法實現(xiàn)的。首先我們看下addSingletonFactory的實現(xiàn)

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

往第三級緩存singletonFactories存放數(shù)據(jù),清除第二級緩存根據(jù)beanName的數(shù)據(jù)。這里有個很重要的點,是往三級緩存里面set了值,這是Spring處理循環(huán)依賴的核心點。getEarlyBeanReference這個方法是getObject的實現(xiàn),可以簡單認為是返回了一個為填充完畢的A的對象實例。設(shè)置完三級緩存后,就開始了填充A對象屬性的過程。下面這段描述,沒有源碼提示,只是簡單的介紹一下。

填充A的時候,發(fā)現(xiàn)需要B類型的Bean,于是繼續(xù)調(diào)用getBean方法創(chuàng)建,記性的流程和上面A的完全一致,然后到了填充C類型的Bean的過程,同樣的調(diào)用getBean(C)來執(zhí)行,同樣到了填充屬性A的時候,調(diào)用了getBean(A),我們從這里繼續(xù)說,調(diào)用了doGetBean中的Object sharedInstance = getSingleton(beanName),相同的代碼,但是處理邏輯完全不一樣了。

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 != NULL_OBJECT ? singletonObject : null);
 }

還是從singletonObjects獲取對象獲取不到,因為A是在singletonsCurrentlyInCreation這個Set中,所以進入了下面的邏輯,從二級緩存earlySingletonObjects中取,還是沒有查到,然后從三級緩存singletonFactories找到對應(yīng)的對象工廠調(diào)用getObject方法獲取未完全填充完畢的A的實例對象,然后刪除三級緩存的數(shù)據(jù),填充二級緩存的數(shù)據(jù),返回這個對象A。C依賴A的實例填充完畢了,雖然這個A是不完整的。不管怎么樣C式填充完了,就可以將C放到一級緩存singletonObjects同時清理二級和三級緩存的數(shù)據(jù)。同樣的流程B依賴的C填充好了,B也就填充好了,同理A依賴的B填充好了,A也就填充好了。Spring就是通過這種方式來解決循環(huán)引用的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Struts2學(xué)習(xí)教程之?dāng)r截器機制與自定義攔截器

    Struts2學(xué)習(xí)教程之?dāng)r截器機制與自定義攔截器

    這篇文章主要給大家介紹了關(guān)于Struts2學(xué)習(xí)基礎(chǔ)教程之?dāng)r截器機制與自定義攔截器的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • Java中的按值傳遞和按引用傳遞的代碼詳解

    Java中的按值傳遞和按引用傳遞的代碼詳解

    本文通過實例代碼給大家介紹了Java中的按值傳遞和按引用傳遞的相關(guān)知識,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-06-06
  • 基于Java中UDP的廣播形式(實例講解)

    基于Java中UDP的廣播形式(實例講解)

    下面小編就為大家分享一篇基于Java中UDP的廣播形式(實例講解),具有很好的參考價值,希望對大家有所幫助
    2017-12-12
  • 詳解Java?加密解密和數(shù)字簽名問題

    詳解Java?加密解密和數(shù)字簽名問題

    在做項目中,只要涉及敏感信息,或者對安全有一定要求的場景,都需要對數(shù)據(jù)進行加密。接下來通過本文給大家分享Java?加密解密和數(shù)字簽名問題,感興趣的朋友跟隨小編一起看看吧
    2021-12-12
  • Java 自定義Spring框架與核心功能詳解

    Java 自定義Spring框架與核心功能詳解

    Spring框架是由于軟件開發(fā)的復(fù)雜性而創(chuàng)建的。Spring使用的是基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅僅限于服務(wù)器端的開發(fā)
    2021-10-10
  • JAVA新手學(xué)習(xí)篇之類和對象詳解

    JAVA新手學(xué)習(xí)篇之類和對象詳解

    這篇文章主要給大家介紹了關(guān)于JAVA新手學(xué)習(xí)篇之類和對象的相關(guān)資料,Java是面向?qū)ο蟮木幊陶Z言,主旨在于通過對象封裝屬性和方法實現(xiàn)功能,面向?qū)ο笈c面向過程的區(qū)別在于關(guān)注點的不同,需要的朋友可以參考下
    2024-10-10
  • JAVA語言編程格式高級規(guī)范

    JAVA語言編程格式高級規(guī)范

    這篇文章主要介紹了JAVA語言編程格式高級規(guī)范,需要的朋友可以參考下
    2015-05-05
  • Spring?Boot中使用Spring?Retry重試框架的操作方法

    Spring?Boot中使用Spring?Retry重試框架的操作方法

    這篇文章主要介紹了Spring?Retry?在SpringBoot?中的應(yīng)用,介紹了RetryTemplate配置的時候,需要設(shè)置的重試策略和退避策略,需要的朋友可以參考下
    2022-04-04
  • java實現(xiàn)抽獎概率類

    java實現(xiàn)抽獎概率類

    這篇文章主要為大家詳細介紹了java實現(xiàn)抽獎概率類,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-11-11
  • Java 給PPT添加動畫效果的示例

    Java 給PPT添加動畫效果的示例

    這篇文章主要介紹了Java 給PPT添加動畫效果的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下
    2021-04-04

最新評論

罗源县| 慈利县| 虹口区| 新巴尔虎右旗| 灵武市| 巴青县| 巩义市| 淳安县| 诸暨市| 贵德县| 蓝山县| 调兵山市| 哈尔滨市| 新竹市| 太康县| 太白县| 来安县| 丘北县| 卫辉市| 南投县| 普兰店市| 自贡市| 高碑店市| 来凤县| 察隅县| 固始县| 巫溪县| 专栏| 兰考县| 车致| 石门县| 荔波县| 禄劝| 永新县| 远安县| 揭东县| 青海省| 育儿| 洛川县| 广河县| 南木林县|