基於springboot bean的實例化過程和屬性註入過程

bean的實例化過程和屬性註入過程

瞭解過springboot的加載流程的都知道springboot初始化bean都在refresh方法中。

這個方法代碼如下:

// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.新建beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
   // Allows post-processing of the bean factory in context subclasses.
   postProcessBeanFactory(beanFactory);
   // Invoke factory processors registered as beans in the context.
   // 加載實現beanFactoryPostProcessor的bean,bean定義的時候執行
   invokeBeanFactoryPostProcessors(beanFactory);
   // Register bean processors that intercept bean creation.
   // 加載實現瞭beanPostProcessor,在bean實例化前、後執行
   registerBeanPostProcessors(beanFactory);
   // Initialize message source for this context.
   initMessageSource();
   // Initialize event multicaster for this context.
   initApplicationEventMulticaster();
   // Initialize other special beans in specific context subclasses.
   onRefresh();
   // Check for listener beans and register them.
   registerListeners();
   // Instantiate all remaining (non-lazy-init) singletons.
   //實例化非懶加載的bean、bean封裝、屬性註入、註解註入(主要使用BeanPostProcessor或子類實現)等
   finishBeanFactoryInitialization(beanFactory);
   // Last step: publish corresponding event.
   finishRefresh();

這裡我們主要看下finishBeanfactoryInitialization方法。此方法實現瞭bean的實例和屬性註入等。進入此方法的最後一行。

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();

註釋寫的很清楚,實例化剩餘非懶加載的bean。此方法的實現是核心類DefaultLisListableBeanFactory實現。這個方法中有個判斷:bean是否是beanFactory的實現類。

如果是則獲取bean的時候會從beanFactory實現類的getObject中獲取,我們重點看看getBean這個方法。

getBean是spring中最重要、最牛逼的方法之一,具體的邏輯是通過doGetBean方法處理的。

我們看下doGetBean方法,方法很長。我們分成幾個部分去看。

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

2、從父beanfactory中獲取

BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
   // Not found -> check parent.
   String nameToLookup = originalBeanName(name);
   if (parentBeanFactory instanceof AbstractBeanFactory) {
      return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
            nameToLookup, requiredType, args, typeCheckOnly);
   }
   else 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);
   }
}

3、直接創建RootBeanDefinition

//mark 給此bean 馬克一下。防止重復創建
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 dep : dependsOn) {
         if (isDependent(beanName, dep)) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
         }
         registerDependentBean(dep, beanName);
         getBean(dep);
      }
   }

4、是singleton還是prototype類型的,根據不同類型去實例化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;
      }
   });
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);

5、檢查bean的類型是否匹配

// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
   try {
      T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
      if (convertedBean == null) {
         throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
      return convertedBean;
   }
   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());
   }
}

整個doGetBean方法改成這5個部分,重點看下第4個部分中的createBean和getObjectForBeanInstance方法。

1、createBean方法,裡面主要是2個部分,bean直接是通過BeanPostProcessor的postProcessBeforeIntantiation方法獲取的。

註釋也是描述的很清楚:Give BeanPostProcessors a chance to return a proxy instead of the bean instance(英語渣渣不敢瞎翻譯誤導大傢,理解就好)

代碼如下:

try {
   // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
   Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
   if (bean != null) {
      return bean;
   }
}
catch (Throwable ex) {
   throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
         "BeanPostProcessor before instantiation of bean failed", ex);
}

第一個部分自己實現,那麼createBean方法第2個部分毋庸置疑肯定是spring去實例化bean,代碼如下:

try {
   Object beanInstance = doCreateBean(beanName, mbdToUse, args);
   if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
   }
   return beanInstance;
}

又是do開頭的方法,說明這個也是一個創建方法,spring中一般do開頭的都是用於創建某個對象。跟著代碼走,看下doCreateBean方法,在查看此方法之前,可能需要瞭解下BeanWarpper這個封裝類。bean的封裝、屬性註入等都是用BeanWarpper去完成的。

看下代碼:

// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
   instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
   instanceWrapper = createBeanInstance(beanName, mbd, args);
}

進入createBeanInstance方法中,就是調用構造器去實例化bean,返回beanWrapper。通過構造器獲取實例代碼如下:

// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
      mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
      mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
   return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);

這裡實例化我一開始以為就是簡單的反射,後面我點進去時候發現裡面一直提策略實例化,我目前瞭解的是可以解決Override的問題等。如果有興趣的可以自行查看。到這裡為止。我們終於實例化bean瞭。下面看下第二步bean的屬性註入等。

代碼如下:

Object exposedObject = bean;
try {
   populateBean(beanName, mbd, instanceWrapper);
   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);
   }
}

populateBean方法名稱就暴露他是幹啥的:填充bean。我放一段比較重要的部分:

if (hasInstAwareBpps || needsDepCheck) {
   if (pvs == null) {
      pvs = mbd.getPropertyValues();
   }
   PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
   if (hasInstAwareBpps) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
            if (pvs == null) {
               return;
            }
         }
      }
   }
   if (needsDepCheck) {
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }
}

這段代碼貌似沒有什麼註入、填充什麼的,我們看下InstantiationAwareBeanPostProcessor這個接口,發現這個接口有個很熟悉的實現類是:AutowiredAnnotationBeanPostProcessor。這個類的方法中我們看到終於看到瞭jnject方法。但是在inject之前需要調用下findAutowiringMatedata方法獲取一下元數據:

// Fall back to class name as cache key, for backwards compatibility with custom callers.
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
   synchronized (this.injectionMetadataCache) {
      metadata = this.injectionMetadataCache.get(cacheKey);
      if (InjectionMetadata.needsRefresh(metadata, clazz)) {
         if (metadata != null) {
            metadata.clear(pvs);
         }
         metadata = buildAutowiringMetadata(clazz);
         this.injectionMetadataCache.put(cacheKey, metadata);
      }
   }
} 
return metadata;

那麼問題又來瞭,這個injectionMetadataCache集合值是從那裡來的呢?AutowiredAnnotationBeanPostProcessor實現瞭MergeBeandefinitionPostProcessor,那麼就好瞭,肯定是在bean實例的時候調用瞭postProcessMergedBeanDefintion這個方法。

果然在doCreateBean方法中有這麼一段:

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
   if (!mbd.postProcessed) {
      try {
         //通過 BeanPostProcessor將需要註解的元數據 放到Map中
         applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      }
      catch (Throwable ex) {
         throw new BeanCreationException(mbd.getResourceDescription(), beanName,
               "Post-processing of merged bean definition failed", ex);
      }
      mbd.postProcessed = true;
   }
}

哎,spring縝密啊。元數據有瞭,下面我們看下element.inject()方法是如何操作的:

if (this.isField) {
   Field field = (Field) this.member;
   ReflectionUtils.makeAccessible(field);
   field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
   if (checkPropertySkipping(pvs)) {
      return;
   }
   try {
      Method method = (Method) this.member;
      ReflectionUtils.makeAccessible(method);
      method.invoke(target, getResourceToInject(target, requestingBeanName));
   }
   catch (InvocationTargetException ex) {
      throw ex.getTargetException();
   }
}

方法簡單明瞭,直接使用反射將值set到屬性中,至此 bean的實例、屬性註入基本完成,下面我們回頭來看doGetBean的另一個方法getObjectForBeanInstance。

2、getObjectForBeanInstance方法。對於是FactoryBean類型的 bean通過getObject獲取到bean的代理實例,跟著方法一直走下去會到getObejct()方法中。

if (System.getSecurityManager() != null) {
   AccessControlContext acc = getAccessControlContext();
   try {
      object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
   }
   catch (PrivilegedActionException pae) {
      throw pae.getException();
   }
}
else {
   //從FactoryBean實現bean中getObejct獲取到bean
   object = factory.getObject();
}

到此 finishBeanfactoryInitialization方法執行結束!

springboot bean實例化流程

bean實例化流程流程是在onRefresh方法的finishBeanFactoryInitialization中。進入該方法

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
                beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(
                    beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
        }
 
        // Register a default embedded value resolver if no bean post-processor
        // (such as a PropertyPlaceholderConfigurer bean) registered any before:
        // at this point, primarily for resolution in annotation attribute values.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }
 
        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);
        }
 
        // Stop using the temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(null);
 
        // Allow for caching all bean definition metadata, not expecting further changes.
        beanFactory.freezeConfiguration();
 
        // Instantiate all remaining (non-lazy-init) singletons.
        beanFactory.preInstantiateSingletons();
    }

1、beanFactory.freezeConfiguration(); 標記正在實例化

當前有183個bean正在實例化中。

2、調用beanFactory.preInstantiateSingletons(); 實例化bean

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: