spring源碼解析bean初始化與依賴注入四

前言java

本文轉自「天河聊技術」微信公衆號spring

本次繼續介紹spring源碼解析bean初始化、依賴注入的部分緩存

 

正文微信

上次介紹到這個方法app

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean這一行ide

//     今早的緩存單例對象以便循環引用
      if (earlySingletonExposure) {
         Object earlySingletonReference = getSingleton(beanName, false);
         if (earlySingletonReference != null) {
            if (exposedObject == bean) {
               exposedObject = earlySingletonReference;
            }
//          初始化的bean沒被包裝又有依賴
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//             獲取依賴的bean
               String[] dependentBeans = getDependentBeans(beanName);
               Set<String> actualDependentBeans = new LinkedHashSet<>(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.");
               }
            }
         }
      }

這一行ui

// Register bean as disposable.註冊的bean做爲可銷燬的
try {
   registerDisposableBeanIfNecessary(beanName, bean, mbd);
}

進入org.springframework.beans.factory.support.AbstractBeanFactory#registerDisposableBeanIfNecessary註冊可銷燬的beanthis

*/
   protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
      AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
//    不是原型模式,能夠銷燬
      if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
//       若是是單例
         if (mbd.isSingleton()) {
            // Register a DisposableBean implementation that performs all destruction
            // work for the given bean: DestructionAwareBeanPostProcessors,
            // DisposableBean interface, custom destroy method.
//          註冊銷燬的bean,這一部分在bean定義解析的部分介紹過,這裏不做介紹了
            registerDisposableBean(beanName,
                  new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
         }
         else {
            // A bean with a custom scope...
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
               throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
//          銷燬後的回調方法
            scope.registerDestructionCallback(beanName,
                  new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
         }
      }
   }

返回org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean這一行prototype

try {
//                   bean初始化
                     return createBean(beanName, mbd, args);
                  }

這裏介紹完了,往下orm

//                    發生異常銷燬單例的bean
                     destroySingleton(beanName);

進入

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#destroySingleton

public void destroySingleton(String beanName) {
      // Remove a registered singleton of the given name, if any.刪除單例的bean,從本地緩存中刪除
      removeSingleton(beanName);

      // Destroy the corresponding DisposableBean instance.
      DisposableBean disposableBean;
      synchronized (this.disposableBeans) {
//       從本地緩存中刪除
         disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
      }
//    bean銷燬的邏輯
      destroyBean(beanName, disposableBean);
   }

這一行

從factoryBean中建立的bean對象
               bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);

這一行

else if (mbd.isPrototype()) {
//             bean定義爲原型模式

這一行

      原型的bean建立以前維護內存中的緩存map映射信息
                  beforePrototypeCreation(beanName);
//                原型的bean建立
                  prototypeInstance = createBean(beanName, mbd, args);

進入

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])這一行

//        bean初始化以前執行beanProccessors
         Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

進入

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

@Nullable
   protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
      Object bean = null;
      if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
         // Make sure bean class is actually resolved at this point.
         if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
//             調用bean初始化前處理器
               bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
               if (bean != null) {
//                bean初始化之後調用處理器
                  bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
               }
            }
         }
         mbd.beforeInstantiationResolved = (bean != null);
      }
      return bean;
   }

返回

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

這一行

//        bean建立
         Object beanInstance = doCreateBean(beanName, mbdToUse, args);

返回

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

這一行

若是類型不一致進行類型轉換
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);

返回

org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons

這一行

for (String beanName : beanNames) {
         Object singletonInstance = getSingleton(beanName);
         if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
               AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
//                單例bean建立完成後回調
                  smartSingleton.afterSingletonsInstantiated();
                  return null;
               }, getAccessControlContext());
            }
            else {
               smartSingleton.afterSingletonsInstantiated();
            }
         }
      }

bean初始化之後觸發回調

這一行

單例bean建立完成後回調
                  smartSingleton.afterSingletonsInstantiated();

返回

org.springframework.context.support.AbstractApplicationContext#refresh

這一行 bean初始化、依賴注入

finishBeanFactoryInitialization(beanFactory);

 

最後

 

本次介紹到這裏,以上內容僅供參考。

相關文章
相關標籤/搜索