麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > Java > 正文

詳解Spring循環依賴的解決方案

2024-07-14 08:41:01
字體:
來源:轉載
供稿:網友

spring針對Bean之間的循環依賴,有自己的處理方案。關鍵點就是三級緩存。當然這種方案不能解決所有的問題,他只能解決Bean單例模式下非構造函數的循環依賴。

我們就從A->B->C-A這個初始化順序,也就是A的Bean中需要B的實例,B的Bean中需要C的實例,C的Bean中需要A的實例,當然這種需要不是構造函數那種依賴。前提條件有了,我們就可以開始了。毫無疑問,我們會先初始化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); //關注點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()) {     //關注點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; }

這個方法很長我們一點點說。先看我們的關注點1 Object sharedInstance = getSingleton(beanName)根據名稱從單例的集合中獲取單例對象,我們看下這個方法,他最終是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); }

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

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

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

下面我們看下關注點2.也是一個getSingleton只不過他是真實的創建Bean的過程,我們可以看到傳入了一個匿名的ObjectFactory的對象,他的getObject方法中調用的是createBean這個真正的創建Bean的方法。當然我們可以先擱置一下,繼續看我們的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)從一級緩存中取數據,肯定是null。隨后就調用的beforeSingletonCreation方法。

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

其中就有往singletonsCurrentlyInCreation這個Set中添加beanName的過程,這個Set很重要,后面會用到。隨后就是調用singletonFactory的getObject方法進行真正的創建過程,下面我們看下剛剛上文提到的真正的創建的過程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.  //關注點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利用反射創建了對象,下面我們看看關注點3 earlySingletonExposure屬性值的判斷,其中有一個判斷點就是isSingletonCurrentlyInCreation(beanName)

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

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

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

填充A的時候,發現需要B類型的Bean,于是繼續調用getBean方法創建,記性的流程和上面A的完全一致,然后到了填充C類型的Bean的過程,同樣的調用getBean(C)來執行,同樣到了填充屬性A的時候,調用了getBean(A),我們從這里繼續說,調用了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找到對應的對象工廠調用getObject方法獲取未完全填充完畢的A的實例對象,然后刪除三級緩存的數據,填充二級緩存的數據,返回這個對象A。C依賴A的實例填充完畢了,雖然這個A是不完整的。不管怎么樣C式填充完了,就可以將C放到一級緩存singletonObjects同時清理二級和三級緩存的數據。同樣的流程B依賴的C填充好了,B也就填充好了,同理A依賴的B填充好了,A也就填充好了。Spring就是通過這種方式來解決循環引用的。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 男人的天堂毛片 | 久久免费看毛片 | 久久人人爽人人爽人人片av高清 | 色网在线视频 | 日产精品一区二区三区在线观看 | 日韩a毛片免费观看 | a免费视频| 撅高 自己扒开 调教 | 免费看日产一区二区三区 | 日韩视频www | 国产精品成aⅴ人片在线观看 | 欧美一级片 在线播放 | 亚洲国产高清视频 | 国产精品欧美久久久久一区二区 | 欧美中文在线 | 久久久国产精品成人免费 | 亚洲一区在线视频观看 | 午夜久久久久 | 久久靖品 | 羞羞视频一区二区 | 亚洲操比视频 | 欧美日韩亚州综合 | 免费毛片小视频 | 欧美成年性h版影视中文字幕 | 国产免费久久久久 | 久久艹精品视频 | 国产成人精品区一区二区不卡 | 一区二区久久久久草草 | 成人短视频在线播放 | 亚洲第一成人在线观看 | 久久99国产伦子精品免费 | 狠狠婷婷综合久久久久久妖精 | 免看黄大片aa | 视频一区二区三区在线播放 | 午夜精品区| 狠狠干精品视频 | 免费国产一级淫片 | 毛片网站网址 | 国产精品性夜天天视频 | 二级大黄大片高清在线视频 | 欧美一区二区三区不卡免费观看 |