首頁 > 軟體

Spring原始碼解析 Bean的範例化

2022-07-07 10:00:18

前言

我們來講一下Bean的範例化過程。這篇文章中,暫時不對Bean迴圈依賴的情況進行分析,因為比較複雜,會放在後面單獨的文章中進行分析。

準備工作

看下面這條語句AnnotationConfigApplicationContext類的refresh方法開始分析,從下面這條語句開始:

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

從官方的註釋可以看出,這裡是用來完成所有非懶載入的bean的範例化過程。

我們先寫一個簡單的bean用於進行測試,其中的Dao也是一個交給spring管理的bean。spring會掃描到這個類,並新增到beanDefinitionMapBeanDefinitionNames中:

@Component
public class MyService {
  @Autowired
  private Dao dao;

  public void query(){
    System.out.println("executing query method");
    dao.query();
  }
}

看一下finishBeanFactoryInitialization中的程式碼:

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  //如果bdMap中存在conversionService,則進行初始化
  //該bean可用來提供資料的轉化功能
  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));
  }
  if (!beanFactory.hasEmbeddedValueResolver()) {
    beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  }
  //初始化型別為LoadTimeWeaverAware的bean
  //可用於AspectJ靜態織入過程
  String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  for (String weaverAwareName : weaverAwareNames) {
    getBean(weaverAwareName);
  }
  //銷燬之前在prepareBeanFactory()中生成的臨時ClassLoader
  beanFactory.setTempClassLoader(null);
  //在這凍結對BeanDefinition的修改
  //防止spring在初始化的時候發生BeanDefinition的修改
  beanFactory.freezeConfiguration();
  beanFactory.preInstantiateSingletons();
}

這個方法中,前面都是在做一些準備工作,直到最後執beanFactorypreInstantiateSingletons方法,才開始準備執行非懶載入的bean的範例化過程。先看preInstantiateSingletons方法的前半段:

public void preInstantiateSingletons() throws BeansException {
  if (logger.isDebugEnabled()) {
    logger.debug("Pre-instantiating singletons in " + this);
  }
  //得到所有bean的名字
  List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  for (String beanName : beanNames) {
    //做了合併父類別的BeanDefinition的操作
    //在會用xml設定bean時 有一個parent 屬性,可以繼承類名,作用域等 
    RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      //判斷是FactoryBean
      if (isFactoryBean(beanName)) {
        //如果是FactoryBean則加上 &
        Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
        if (bean instanceof FactoryBean) {
          final FactoryBean<?> factory = (FactoryBean<?>) bean;
          boolean isEagerInit;
          if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                    ((SmartFactoryBean<?>) factory)::isEagerInit,
                getAccessControlContext());
          }
          else {
            isEagerInit = (factory instanceof SmartFactoryBean &&
                ((SmartFactoryBean<?>) factory).isEagerInit());
          }
          if (isEagerInit) {
            getBean(beanName);
          }
        }
      }
      else { //不是factoryBean的情況
        getBean(beanName);
      }
    }
  }
  ...

首先從beanDefinitionNames的List中拿到所有的beanName,進行遍歷。之前講過DefaultListableBeanFactory內部快取了一個beanDefinitionMap的Map,和這個beanDefinitionNames的List,從這也可以看出,通過適當的冗餘可以一定程度上減少編碼中的工作量。

在對bean進行初始化前包含3個條件:不能為抽象類、單例bean、以及非懶載入。非常好理解不再多說,重點說明一下通過isFactoryBean方法判斷bean是否FactorybeanFactorybean是一個比較特殊的bean,並且受spring容器管理,看一下介面定義:

public interface FactoryBean<T> {
  T getObject() throws Exception;
  Class<?> getObjectType();
  default boolean isSingleton() {
    return true;
  }
}

如果一個類實現了FactoryBean介面,那個spring容器中會存在兩個物件,一個是getObject方法返回的物件,另一個是當前FactoryBean物件本身,並且用&新增在beanName前進行區分。舉個例子:

@Component
public class MyFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new TestDao();
    }
    @Override
    public Class<?> getObjectType() {
        return TestDao.class;
    }
}

測試:

System.out.println(context.getBean("myFactoryBean"));
System.out.println(context.getBean("&myFactoryBean"));

結果:

com.hydra.dao.TestDao@fbd1f6
com.hydra.factorybean.MyFactoryBean@1ce24091

對於FactoryBean的獲取,要在beanName前加上一個字首&,然後會先判斷是否是SmartFactoryBean並且isEagerInit為true,如果是才呼叫getBean方法進行初始化。此處內容略過,直接看重要的getBean方法:

public Object getBean(String name) throws BeansException {
  return doGetBean(name, null, null, false);
}

此處為空方法,繼續呼叫doGetBean方法,從這開始為範例化bean的核心流程。

範例化bean

為了方便分析,我們將類與方法按照呼叫順訊進行編號,方便後面解析流程的分析。

1、AbstractBeanFactory 的 doGetBean方法

和以前一樣,非重點的內容直接在程式碼中用註釋解釋。

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
    @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
  final String beanName = transformedBeanName(name);
  Object bean;
  //先嚐試從spring容器中獲取一次,如果為空則範例化
  Object sharedInstance = getSingleton(beanName);
  //在呼叫getBean時,args為空
  //如果不為空,那麼意味著呼叫方不是希望獲取bean,而是建立bean
  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,下面的方法會直接返回sharedInstance
    *  但如果是FactoryBean 型別的,則需要getObject工廠方法獲得bean範例
    *  如果想獲取FactoryBean本身,也不會做特別的處理
    * */
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  }
  else {
    //如果當前執行緒已經建立過了prototype型別的這個bean,丟擲異常
    if (isPrototypeCurrentlyInCreation(beanName)) {
      throw new BeanCurrentlyInCreationException(beanName);
    }
    // 如果對spring沒有進行改造,這裡預設 parentBeanFactory為空
    BeanFactory parentBeanFactory = getParentBeanFactory();
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
      String nameToLookup = originalBeanName(name);
      if (parentBeanFactory instanceof AbstractBeanFactory) {
        return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
            nameToLookup, requiredType, args, typeCheckOnly);
      }
      else if (args != null) {
        return (T) parentBeanFactory.getBean(nameToLookup, args);
      }
      else {
        return parentBeanFactory.getBean(nameToLookup, requiredType);
      }
    }
    if (!typeCheckOnly) {
      //typeCheckOnly為false,新增到alreadyCreated Set集合當中,表示它已經建立過
      //防止重複建立
      markBeanAsCreated(beanName);
    }
    //重點部分,建立singleton的bean,或建立新的prototype的bean
    try {
      final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
      checkMergedBeanDefinition(mbd, beanName, args);

      // 判斷當前bean是否有依賴,這裡指的是使用depends-on的情況,需要先範例化依賴bean
      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);
          try {
            //初始化被依賴bean
            getBean(dep);
          }
          catch (NoSuchBeanDefinitionException ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
          }
        }
      } 
      //在這才真正建立bean的範例
      if (mbd.isSingleton()) {
        sharedInstance = getSingleton(beanName, () -> {
          try {
            //真正建立功能的語句
            return createBean(beanName, mbd, args);
          }
          catch (BeansException ex) {            
            destroySingleton(beanName);
            throw ex;
          }
        });
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
      }
      // 建立 prototype 的範例
      else if (mbd.isPrototype()) {        
        Object prototypeInstance = null;
        try {
          beforePrototypeCreation(beanName);
          prototypeInstance = createBean(beanName, mbd, args);
        }
        finally {
          afterPrototypeCreation(beanName);
        }
        bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
      }
      //如果不是singleto和prototype,委託給相應的實現類來處理
      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, () -> {
            beforePrototypeCreation(beanName);
            try {
              return createBean(beanName, mbd, args);
            }
            finally {
              afterPrototypeCreation(beanName);
            }
          });
          bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
        }
      //丟擲異常,程式碼省略...
  }
  //型別檢查,正常則返回,異常則丟擲
  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());
    }
  }
  return (T) bean;
}

在建立bean前,首先呼叫了DefaultSingletonBeanRegistrygetSingleton方法,也就是說spring在初始化一個bean前先去嘗試獲取一次,判斷這個物件是否已經被範例化好了,如果已經存在就直接拿過來用。進入getSingleton方法,核心程式碼:

Object singletonObject = this.singletonObjects.get(beanName);

看一下singletonObjects的定義:

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

這裡提前劇透一下,這個Map就是用於存放範例化好的單例bean,並且從狹義上來說,可以說這個singletonObjects就是spring容器,並且它使用了ConcurrentHashMap,來保證並行操作的安全性。

因為我們的bean還處於建立階段,那麼這一次是肯定不能從Map獲取到範例的,那麼接著向下執行,看一下呼叫的createBean方法。

2、AbstractAutowireCapableBeanFactory 的 createBean方法

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {
  if (logger.isDebugEnabled()) {
    logger.debug("Creating instance of bean '" + beanName + "'");
  }
  RootBeanDefinition mbdToUse = mbd;
  //確保 BeanDefinition 中的 Class 被載入
  Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
    mbdToUse = new RootBeanDefinition(mbd);
    mbdToUse.setBeanClass(resolvedClass);
  }
  // 處理 lookup-method 和 replace-method 設定
  // spring中把lookup-method 和 replace-method 統稱為method overrides
  try {
    mbdToUse.prepareMethodOverrides();
  }
  catch (BeanDefinitionValidationException ex) {
    throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
        beanName, "Validation of method overrides failed", ex);
  }
  try {
    //應用後置處理器,如果後置處理器返回的bean不為空則直接返回
    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);
  }
  try {//呼叫doCreateBean建立bean
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
  }
  //非重要程式碼省略...
}

前面做了很長的鋪墊工作,但還是沒有建立bean,建立bean的工作被交給了doCreateBean方法完成。

3、AbstractAutowireCapableBeanFactory 的 doCreateBean方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
    throws BeanCreationException {
  //BeanWrapper是一個包裝介面,真正範例化的是 BeanWrapperImpl
  BeanWrapper instanceWrapper = null;
  if (mbd.isSingleton()) {
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  }
  if (instanceWrapper == null) {
    //建立bean範例,並將範例包裹在 BeanWrapper 實現類物件中返回
    instanceWrapper = createBeanInstance(beanName, mbd, args);
  }
  // 使用BeanWrapper 產生一個原生物件
  final Object bean = instanceWrapper.getWrappedInstance();
  Class<?> beanType = instanceWrapper.getWrappedClass();
  if (beanType != NullBean.class) {
    mbd.resolvedTargetType = beanType;
  }
  // Allow post-processors to modify the merged bean definition.
  synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
      try {
        //執行後置處理器MergedBeanDefinitionPostProcessor
        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      }
      catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Post-processing of merged bean definition failed", ex);
      }
      mbd.postProcessed = true;
    }
  }
  //用於處理迴圈依賴,後面單獨分析
  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, () -> getEarlyBeanReference(beanName, mbd, bean));
  }
  //到此為止,還是原生物件
  Object exposedObject = bean;
  try {
    //賦值屬性,依賴,非常重要
    populateBean(beanName, mbd, instanceWrapper);
    //執行後置處理器,變成代理物件,aop就是在這裡完成的處理  
    exposedObject = initializeBean(beanName, exposedObject, mbd);
  }
  //中間非重要程式碼省略...
  return exposedObject;
}

這裡面做了三個比較重要的工作:

  • ①、呼叫createBeanInstance方法建立bean範例
  • ②、呼叫populateBean進行屬性的填充,依賴注入就是在這裡完成
  • ③、呼叫initializeBean,執行各種後置處理器,執行各種回撥函數

我們按照順序,先接著講①中建立bean勢力的過程,等這個過程完了再回頭分析屬性填充和回撥方法。

4、AbstractAutowireCapableBeanFactory 的 createBeanInstance方法

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  //確保載入了該class
  Class<?> beanClass = resolveBeanClass(mbd, beanName);

  //檢測一個類的存取許可權 spring預設情況下對於public的類是允許存取的
  if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
        "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  }

  Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  if (instanceSupplier != null) {
    return obtainFromSupplier(instanceSupplier, beanName);
  }

  /*
  *如果工廠方法不為空,則通過工廠方法構建bean物件
  * factoryMethod基於xml,實際工作中很少使用
  *  */
  if (mbd.getFactoryMethodName() != null) {
    return instantiateUsingFactoryMethod(beanName, mbd, args);
  }

  /*
  * 從spring的原始註釋可以知道這個是一個ShortCut,當多次構建同一個bean時,可以使用這個ShortCut
  * 這裡的resolved和 mbd.constructorArgumentsResolved 將會在bean第一次範例化的過程中被設定
  * */
  boolean resolved = false;
  boolean autowireNecessary = false;
  if (args == null) {
    synchronized (mbd.constructorArgumentLock) {
      if (mbd.resolvedConstructorOrFactoryMethod != null) {
        resolved = true;
        //如果已經解析了構造方法的引數,則必須要通過一個帶引數構造方法來範例
        autowireNecessary = mbd.constructorArgumentsResolved;
      }
    }
  }
  if (resolved) {
    if (autowireNecessary) {
      //通過構造方法自動裝配的方式構造bean物件
      return autowireConstructor(beanName, mbd, null, null);
    }
    else {
      //通過預設的無參構造方法進行
      return instantiateBean(beanName, mbd);
    }
  }

  //spring目前不知道用什麼方式範例化這個bean,所以先拿到所有的構造方法
  //由後置處理器決定返回哪些構造方法
  Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  /*
  * AUTOWIRE :  0-NO  ,1-BY_NAME,2-BY_TYPE,3-CONSTRUCTOR
  * 在這裡mbd.getResolvedAutowireMode()取到的是0,就是NO
  * */
  if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
      mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
    return autowireConstructor(beanName, mbd, ctors, args);
  }
  //使用預設的無參構造方法進行初始化
  return instantiateBean(beanName, mbd);
}

如果bean擁有多個構造方法的話,會根據引數去判斷具體使用哪一個,具體內容比較複雜,準備以後放在一篇單獨的文章中進行分析。如果只有無參構造方法或不寫構造方法的話,都會預設使用無參構造方法進行範例化,這裡暫時只對這種情況進行分析。

5、AbstractAutowireCapableBeanFactory 的 instantiateBean方法

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  try {
    Object beanInstance;
    final BeanFactory parent = this;
    if (System.getSecurityManager() != null) {
      beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
          getInstantiationStrategy().instantiate(mbd, beanName, parent),
          getAccessControlContext());
    }
    else {
      // getInstantiationStrategy得到類的範例化策略
      beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
    }
    BeanWrapper bw = new BeanWrapperImpl(beanInstance);
    initBeanWrapper(bw);
    return bw;
  }
  catch (Throwable ex) {
    throw new BeanCreationException(
        mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  }
}

這裡通過getInstantiationStrategy得到類的範例化策略,預設情況下是得到一個反射的範例化策略。然後呼叫instantiate方法進行範例化。

6、SimpleInstantiationStrategy 的 instantiate方法

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  // 檢測bean設定中是否設定了lookup-method 或 replace-method
  //如果設定了就需使用CGLIB構建bean物件
  if (!bd.hasMethodOverrides()) {
    Constructor<?> constructorToUse;
    synchronized (bd.constructorArgumentLock) {
      constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
      if (constructorToUse == null) {
        final Class<?> clazz = bd.getBeanClass();
        if (clazz.isInterface()) {
          throw new BeanInstantiationException(clazz, "Specified class is an interface");
        }
        try {
          if (System.getSecurityManager() != null) {
            constructorToUse = AccessController.doPrivileged(
                (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
          }
          else {
            //得到預設構造方法,即使沒有寫也會有一個
            constructorToUse = clazz.getDeclaredConstructor();
          }
          bd.resolvedConstructorOrFactoryMethod = constructorToUse;
        }
        catch (Throwable ex) {
          throw new BeanInstantiationException(clazz, "No default constructor found", ex);
        }
      }
    }               
    //使用構造方法進行範例化
    return BeanUtils.instantiateClass(constructorToUse);
  }
  else {
    //使用CGLIB進行範例化
    return instantiateWithMethodInjection(bd, beanName, owner);
  }
}

instantiateClass方法中,通過反射建立物件:

//設定構造方法為可存取
ReflectionUtils.makeAccessible(ctor);
//反射建立物件
return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
   KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));

執行到這,範例化的過程就完成了,但是目前屬性還沒有注入,回到開頭我們舉的那個例子,其中還有一個Dao沒有被注入,下一篇文章,我們接下來分析屬性的注入。

到此這篇關於Spring原始碼解析 Bean的範例化的文章就介紹到這了,更多相關Spring Bean範例化內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com