天天看點

你知道Spring是怎麼将AOP應用到Bean的生命周期中的嗎? 前言 Bean生命周期中AOP的流程 總結 Spring源碼的最後一點補充

聊一聊Spring是怎麼将AOP應用到Bean的生命周期中的?

本系列文章:

聽說你還沒學Spring就被源碼編譯勸退了?30+張圖帶你玩轉Spring編譯 讀源碼,我們可以從第一行讀起 你知道Spring是怎麼解析配置類的嗎? 配置類為什麼要添加@Configuration注解? 談談Spring中的對象跟Bean,你知道Spring怎麼建立對象的嗎? 這篇文章,我們來談一談Spring中的屬性注入 Spring中AOP相關的API及源碼解析,原來AOP是這樣子的 推薦閱讀: Spring官網閱讀 | 總結篇 Spring雜談

本系列文章将會帶你一行行的将Spring的源碼吃透,推薦閱讀的文章是閱讀源碼的基礎!

前言

在上篇文章中(

)我們已經分析過了AOP的實作的源碼,那麼Spring是如何将AOP應用到Bean的生命周期的呢?這篇文章就帶着大家來探究下這個問題。本文我們要分析的代碼還是位于

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

這個方法中,在《

我們來談一談Spring中的屬性注入

》這篇文章中,我們已經分析過了

populateBean

這個方法,

image-20200703202825887

是以本文我們接着來看看

initializeBean

這個方法,它主要幹了這麼幾件事

  1. 執行

    Aware

    接口中的方法
  2. 生命周期回調方法

  3. 完成

    AOP

    代理

對應源碼如下:

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  if (System.getSecurityManager() != null) {
   AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    invokeAwareMethods(beanName, bean);
    return null;
   }, getAccessControlContext());
  }
  else {
           
            // 執行Aware接口中的方法
   invokeAwareMethods(beanName, bean);
  }

  Object wrappedBean = bean;
  if (mbd == null || !mbd.isSynthetic()) {
            
            // 調用InitDestroyAnnotationBeanPostProcessor
            // 的postProcessBeforeInitialization方法
            // 處理@PostContructor注解标注的方法
            // 另外有一部分aware方法也是在這裡調用的
   wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  }

  try {
            // 如果實作了InitializingBean,會調用afterPropertiesSet方法
            // 如果XML中配置了init-method屬性,會調用對應的初始化方法
   invokeInitMethods(beanName, wrappedBean, mbd);
  }
  catch (Throwable ex) {
   throw new BeanCreationException(
     (mbd != null ? mbd.getResourceDescription() : null),
     beanName, "Invocation of init method failed", ex);
  }
  if (mbd == null || !mbd.isSynthetic()) {
            // 在這裡完成AOP
   wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  }

  return wrappedBean;
 }
           

因為在

Spring官網閱讀(九)Spring中Bean的生命周期(上)

文章中我們已經對這個方法做過分析了,并且這個方法本身也比較簡單,是以不再對這個方法做過多贅述,我們主要關注的就是Spring是如何将

AOP

應用到Bean的生命周期中的,對應的就是

applyBeanPostProcessorsAfterInitialization

這個方法,其源碼如下:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
    throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessAfterInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}
           

實際上就是調用了所有後置處理器的

postProcessAfterInitialization

方法,在

一文中已經提到過了,

@EnableAspectJAutoProxy

注解實際上就是向容器中注冊了一個

AnnotationAwareAspectJAutoProxyCreator

,這個類本身就是一個後置處理器,

AOP代理

就是由它在這一步完成的。

Bean生命周期中AOP的流程

1、@EnableAspectJAutoProxy

通過

@EnableAspectJAutoProxy

注解向容器中注冊一個

AnnotationAwareAspectJAutoProxyCreator

BeanDefinition

,它本身也是一個

BeanPostProcessor

,這個

BeanDefinition

會在

org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors

這個方法中完成建立,如下圖所示

image-20200704112937846

2、postProcessBeforeInstantiation方法執行

AnnotationAwareAspectJAutoProxyCreator

postProcessBeforeInstantiation

方法,實際上就是父類

AbstractAutoProxyCreator

postProcessBeforeInstantiation

被執行

//  這個方法的主要目的就是在不考慮通知的情況下,确認哪些Bean不需要被代理
//  1.Advice,Advisor,Pointcut類型的Bean不需要被代理
//  2.不是原始Bean被包裝過的Bean不需要被代理,例如ScopedProxyFactoryBean
//  實際上并不隻是這些Bean不需要被代理,如果沒有對應的通知需要被應用到這個Bean上的話
//  這個Bean也是不需要被代理的,隻不過不是在這個方法中處理的。
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
    Object cacheKey = getCacheKey(beanClass, beanName);
    // 如果beanName為空或者為這個bean提供了定制的targetSource
    if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
        // advisedBeans是一個map,其中key是BeanName,value代表了這個Bean是否需要被代理
        // 如果已經包含了這個key,不需要在進行判斷了,直接傳回即可
        // 因為這個方法的目的就是在執行個體化前就确認哪些Bean是不需要進行AOP的
        if (this.advisedBeans.containsKey(cacheKey)) {
            return null;
        }
        // 說明還沒有對這個Bean進行處理
        // 在這裡會對SpringAOP中的基礎設施bean,例如Advice,Pointcut,Advisor做标記
        // 标志它們不需要被代理,對應的就是将其放入到advisedBeans中,value設定為false
        // 其次,如果這個Bean不是最原始的Bean,那麼也不進行代理,也将其value設定為false
        if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return null;
        }
    }

    // 是否為這個Bean提供了定制的TargetSource
    // 如果提供了定制的TargetSource,那麼直接在這一步建立一個代理對象并傳回
    // 一般不會提供
    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
    if (targetSource != null) {
        if (StringUtils.hasLength(beanName)) {
            this.targetSourcedBeans.add(beanName);
        }
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
        Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    return null;
}
           

3、postProcessAfterInitialization方法執行

實際上也是執行父類

AbstractAutoProxyCreator

中的方法,對應源碼如下:

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        // 什麼時候這個判斷會成立呢?
        // 如果不出現循環引用的話,remove方法必定傳回null
        // 是以這個remove(cacheKey) != bean肯定會成立
        // 如果發生循環依賴的話,這個判斷就不會成立
        // 這個我們在介紹循環依賴的時候再詳細分析,
        // 目前你隻需要知道wrapIfNecessary完成了AOP代理
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            // 需要代理的話,在這裡完成的代理
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}
           

4、wrapIfNecessary方法執行

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
   
    // 在postProcessBeforeInstantiation方法中可能已經完成過代理了
    // 如果已經完成代理了,那麼直接傳回這個代理的對象
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    
    // 在postProcessBeforeInstantiation方法中可能已經将其标記為不需要代理了
    // 這種情況下,也直接傳回這個Bean
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    
    // 跟在postProcessBeforeInstantiation方法中的邏輯一樣
    // 如果不需要代理,直接傳回,同時在advisedBeans中标記成false
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // 擷取可以應用到這個Bean上的通知
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    // 如果存在通知的話,說明需要被代理
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        // 到這裡建立代理,實際上底層就是new了一個ProxyFactory來建立代理的
        Object proxy = createProxy(
            bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
 // 如果沒有通知的話,也将這個Bean标記為不需要代理
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
           

關于建立代理的具體源碼分析,在

一文中已經做了詳細介紹,是以本文不再贅述,現在我們的重點将放在Spring是如何解析出來通知的,對應方法就是

getAdvicesAndAdvisorsForBean

,其源碼如下:

第一步:調用

org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean

protected Object[] getAdvicesAndAdvisorsForBean(
      Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
  
   // 通過findEligibleAdvisors方法傳回對應的通知
   // 這個方法回傳回所有能應用在指定的Bean上的通知
   List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
   
   if (advisors.isEmpty()) {
      return DO_NOT_PROXY;
   }
   return advisors.toArray();
}
           

第二步:調用

org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors

protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    // 擷取到所有的通知
    List<Advisor> candidateAdvisors = findCandidateAdvisors();
    // 從擷取到的通知中篩選出能應用到這個Bean上的通知
    List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    extendAdvisors(eligibleAdvisors);
    if (!eligibleAdvisors.isEmpty()) {
        eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return eligibleAdvisors;
}
           

第三步:調用

org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors

擷取到所有的通知

// 這個方法的目的就是為了擷取到所有的通知
protected List<Advisor> findCandidateAdvisors() {
   
    // 先調用父類的方法,父類會去查找容器中所有屬于Advisor類型的Bean
    List<Advisor> advisors = super.findCandidateAdvisors();
    
   // 這個類本身會通過一個aspectJAdvisorsBuilder來建構通知
    // 建構的邏輯就是解析@Aspect注解所标注的類中的方法
    if (this.aspectJAdvisorsBuilder != null) {
        advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
    }
    
    // 最後傳回這些通知
    return advisors;
}
           

第四步:

org.springframework.aop.aspectj.annotation.BeanFactoryAspectJAdvisorsBuilder#buildAspectJAdvisors

建構通知,這個方法比較長,我們就隻分析其中的關鍵代碼即可

public List<Advisor> buildAspectJAdvisors() {
  List<String> aspectNames = this.aspectBeanNames;

  if (aspectNames == null) {
   synchronized (this) {
    aspectNames = this.aspectBeanNames;
    if (aspectNames == null) {
     List<Advisor> advisors = new ArrayList<>();
     aspectNames = new ArrayList<>();
     // 會擷取到容器中的所有BeanName
     String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
       this.beanFactory, Object.class, true, false);
     for (String beanName : beanNames) {
      // 如果對beanName配置了正則比對的話,那麼要按照正規表達式的比對規則進行過濾
      // 預設是沒有的,可以認為isEligibleBean始終傳回true
      if (!isEligibleBean(beanName)) {
       continue;
      }
      // We must be careful not to instantiate beans eagerly as in this case they
      // would be cached by the Spring container but would not have been weaved.
      Class<?> beanType = this.beanFactory.getType(beanName);
      if (beanType == null) {
       continue;
      }
      // 判斷類上是否添加了@Aspect注解
      if (this.advisorFactory.isAspect(beanType)) {
       aspectNames.add(beanName);
       AspectMetadata amd = new AspectMetadata(beanType, beanName);
       // 預設就是SINGLETON,代理切面對象是單例的
       if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
                            // 最後從這個切面執行個體中解析出所有的通知
                            // 關于通知解析的具體代碼就不再分析了
         MetadataAwareAspectInstanceFactory factory =
          new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
        List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
        if (this.beanFactory.isSingleton(beanName)) {
         this.advisorsCache.put(beanName, classAdvisors);
        }
        else {
         this.aspectFactoryCache.put(beanName, factory);
        }
        advisors.addAll(classAdvisors);
       }
  // 省略部分代碼
  return advisors;
 }

           

第五步:

org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply

protected List<Advisor> findAdvisorsThatCanApply(
    List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {

    ProxyCreationContext.setCurrentProxiedBeanName(beanName);
    try {
        return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
    }
    finally {
        ProxyCreationContext.setCurrentProxiedBeanName(null);
    }
}
           

這個方法其實沒啥好分析的,就是根據前面找出來的

Advisor

集合進行周遊,然後根據每個

Advisor

對應的切點來進行比對,如何合适就傳回,對應源碼也比較簡單,當然前提是你看過我之前那篇

AOP源碼分析

的文章了.

總結

這篇文章比較短,因為沒有做很細節的源碼分析,比較詳細的源碼分析已經放到上篇文章中了。最後我這裡畫個流程圖總結一下AOP是怎麼被應用到Bean的生命周期中的

image-20200705152704917

Spring源碼的最後一點補充

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {
    // 1.執行個體化    ---> createBeanInstance
    // 2.屬性注入  ---> populateBean
    // 3.初始化    ---> 完成初始化及AOP
    // exposedObject 就是完成初始化後的Bean  
    // 省略部分代碼,省略代碼的作用已經在上面标明了
    
    // 下面的代碼實際上主要目的在于處理循環依賴
    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            // 我們之前早期暴露出去的Bean跟現在最後要放到容器中的Bean不是同一個
            // allowRawInjectionDespiteWrapping為false
            // 并且目前Bean被當成依賴注入到了别的Bean中
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                // 擷取到目前Bean所從屬的Bean
                String[] dependentBeans = getDependentBeans(beanName);
                // 要得到真實的從屬的Bean
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    // 移除那些僅僅為了類型檢查而建立出來
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
     // 抛出異常
                    // 出現了循環依賴,并且實際存在容器中的Bean跟被當作依賴注入到别的Bean中的
                    // 不是同一個對象,這個時候也報錯
                }
            }
        }
    }

    // 注冊bean的銷毀回調
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}
           

實際這段代碼還是跟循環依賴相關,循環依賴是Spring中一個比較重要的話題,不管是為了面試還是更好的了解清楚Spring的流程都很有必要去弄懂它

關于Spring的循環依賴,我将在下篇文章專門分析!

本文使用

mdnice

排版