AOP源碼解析:AspectJAwareAdvisorAutoProxyCreator類的介紹

AspectJAwareAdvisorAutoProxyCreator 的類圖

上圖中一些 類/接口 的介紹:html

AspectJAwareAdvisorAutoProxyCreator : 公開了AspectJ的調用上下文,並弄清楚來自同一切面的多個Advisor在AspectJ中的優先級規則。java

AbstractAdvisorAutoProxyCreator : 通用自動代理建立器,它基於檢測到的每一個顧問程序爲特定bean構建AOP代理。git

AbstractAutoProxyCreator擴展了 ProxyProcessorSupport,實現了SmartInstantiationAwareBeanPostProcessor、BeanFactoryAware 接口,是BeanPostProcessor 實現,該實現使用AOP代理包裝每一個合格的bean,並在調用bean自己以前委派給指定的攔截器。github

BeanFactoryAware : 實現了該接口的Bean能夠知道它屬於那個 BeanFactory,Bean能夠經過Spring容器查找它的協同者(依賴查找),但大多數的Bean是經過構造器參數和Bean方法(依賴注入)來獲取它的協同者。spring

BeanPostProcessor :工廠鉤子,容許自定義修改新的bean實例。例如,檢查標記接口或使用代理包裝bean。若是咱們須要在Spring容器中完成Bean的實例化,配置和其初始化先後添加一些本身的邏輯處理,咱們就能夠定義一個或多個BeanPostProcessor接口的實現,而後註冊到容器中。緩存

InstantiationAwareBeanPostProcessor :  BeanPostProcessor 的子接口,它添加了實例化以前的回調,以及實例化以後但設置了顯式屬性或自動裝配以前的回調。它內部提供了3個方法,再加上BeanPostProcessor接口內部的2個方法,實現這個接口須要實現5個方法。InstantiationAwareBeanPostProcessor 接口的主要做用在於目標對象的實例化過程當中須要處理的事情,包括實例化對象的先後過程以及實例的屬性設置。ide

SmartInstantiationAwareBeanPostProcessorInstantiationAwareBeanPostProcessor 接口的擴展,多出了3個方法,添加了用於預測已處理bean的最終類型的回調,再加上父接口的5個方法,因此實現這個接口須要實現8個方法,主要做用也是在於目標對象的實例化過程當中須要處理的事情。源碼分析

AspectJAwareAdvisorAutoProxyCreator爲 AspectJ 切面類建立自動代理。post

 

  BeanPostProcessor 接口中的兩個方法 postProcessBeforeInitialization 和 postProcessAfterInitialization,做用是對Bean初始化先後添加一些本身的邏輯。ui

1     @Nullable
2     default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
3         return bean;
4     }
5 
6     @Nullable
7     default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
8         return bean;
9     }

  InstantiationAwareBeanPostProcessor 是 BeanPostProcessor 的子接口,它額外增長了3個新的方法:postProcessBeforeInstantiation( 目標對象被實例化以前調用的方法,能夠返回目標實例的一個代理用來代替目標實例 )、postProcessAfterInstantiation(該方法在Bean實例化以後執行,返回false,會忽略屬性值的設置;若是返回true,會按照正常流程設置屬性值) 和 postProcessPropertyValues(對屬性值進行修改,將來版本將會刪除)。

 1     @Nullable
 2     default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
 3         return null;
 4     }
 5 
 6     default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
 7         return true;
 8     }
 9 
10     @Nullable
11     default PropertyValues postProcessPropertyValues(
12             PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
13 
14         return pvs;
15     }

  SmartInstantiationAwareBeanPostProcessor接口繼承InstantiationAwareBeanPostProcessor接口,裏面定義了3個方法:predictBeanType(預測Bean的類型)、determineCandidateConstructors(選擇合適的構造器)、getEarlyBeanReference(解決循環引用問題)。

 1     @Nullable
 2     default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
 3         return null;
 4     }
 5 
 6     @Nullable
 7     default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
 8         return null;
 9     }
10 
11     default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
12         return bean;
13     }

  AbstractAutoProxyCreator 是AOP的一個核心類,它實現了SmartInstantiationAwareBeanPostProcessor、BeanFactoryAware 接口,實現了代理建立的邏輯,使用AOP代理包裝每一個合格的bean,並在調用bean自己以前委派給指定的攔截器。

  AbstractAdvisorAutoProxyCreator 通用自動代理建立器,它基於檢測每一個bean的加強器,爲特殊的bean構建AOP代理。子類能夠重寫此findCandidateAdvisors()方法,以返回適用於任何對象的advisor的自定義列表,子類還能夠重寫繼承的AbstractAutoProxyCreator.shouldSkip()方法,以將某些對象排除在自動代理以外。

1     protected List<Advisor> findCandidateAdvisors() {
2         Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
3         return this.advisorRetrievalHelper.findAdvisorBeans();
4     }

  AspectJAwareAdvisorAutoProxyCreator 擴展 AbstractAdvisorAutoProxyCreator,公開了AspectJ的調用上下文,並在多個加強器來自同一切面時搞清楚AspectJ的建議優先級順序。按AspectJ優先級排序其他部分:

 1     @Override
 2     @SuppressWarnings("unchecked")
 3     protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
 4         List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size());
 5         for (Advisor element : advisors) {
 6             partiallyComparableAdvisors.add(
 7                     new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR));
 8         }
 9         List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors);
10         if (sorted != null) {
11             List<Advisor> result = new ArrayList<>(advisors.size());
12             for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {
13                 result.add(pcAdvisor.getAdvisor());
14             }
15             return result;
16         }
17         else {
18             return super.sortAdvisors(advisors);
19         }
20     }

  在加強鏈頭部增長一個ExposeInvocationInterceptor,使用AspectJ表達式切入點和使用AspectJ樣式的advisor時,須要這些附加advisor。

1     protected void extendAdvisors(List<Advisor> candidateAdvisors) {
2         AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
3     }

  若是此後處理器不該該考慮將給定的bean用於自動代理,子類應重寫此方法以返回true

 1     @Override
 2     protected boolean shouldSkip(Class<?> beanClass, String beanName) {
 3         // TODO: Consider optimization by caching the list of the aspect names
 4         List<Advisor> candidateAdvisors = findCandidateAdvisors();
 5         for (Advisor advisor : candidateAdvisors) {
 6             if (advisor instanceof AspectJPointcutAdvisor &&
 7                     ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
 8                 return true;
 9             }
10         }
11         return super.shouldSkip(beanClass, beanName);
12     }

  AspectJAwareAdvisorAutoProxyCreator 還有一個子類叫 AnnotationAwareAspectJAutoProxyCreator,子類AnnotationAwareAspectJAutoProxyCreator是用於處理當前應用程序上下文中的全部AspectJ註釋方面以及Spring Advisor。若是Spring AOP的基於代理的模型可以應用任何AspectJ註釋的類,它們的advisor將被自動識別,這涵蓋了方法執行鏈接點,Spring Advisor的處理遵循AbstractAdvisorAutoProxyCreator中創建的規則。

生成代理對象

  從使用<aop:xxx>標籤來自動生成代理的話,先看看AopNamespaceHandler,使用<aop:config>標籤則使用 ConfigBeanDefinitionParser 解析,使用了<aop:aspectj-autoproxy>標籤則使用 AspectJAutoProxyBeanDefinitionParser 解析,依次類推。

 1     @Override
 2     public void init() {
 3         // In 2.0 XSD as well as in 2.1 XSD.
 4         registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser());
 5         registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
 6         registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator());
 7 
 8         // Only in 2.0 XSD: moved to context namespace as of 2.1
 9         registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
10     }
  • <aop:config>方式使用 AspectJAwareAdvisorAutoProxyCreator 建立代理

  • <aop:aspectj-autoproxy>使用 AnnotationAwareAspectJAutoProxyCreator 建立代理

ConfigBeanDefinitionParser.java

 1     @Override
 2     @Nullable
 3     public BeanDefinition parse(Element element, ParserContext parserContext) {
 4         CompositeComponentDefinition compositeDef =
 5                 new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element));
 6         parserContext.pushContainingComponent(compositeDef);
 7 
 8         configureAutoProxyCreator(parserContext, element); // 註冊AspectJAwareAdvisorAutoProxyCreator
 9 
10         List<Element> childElts = DomUtils.getChildElements(element);
11         for (Element elt: childElts) {
12             String localName = parserContext.getDelegate().getLocalName(elt);
13             if (POINTCUT.equals(localName)) {
14                 parsePointcut(elt, parserContext);
15             }
16             else if (ADVISOR.equals(localName)) {
17                 parseAdvisor(elt, parserContext);
18             }
19             else if (ASPECT.equals(localName)) {
20                 parseAspect(elt, parserContext);
21             }
22         }
23 
24         parserContext.popAndRegisterContainingComponent();
25         return null;
26     }
27 
28     private void configureAutoProxyCreator(ParserContext parserContext, Element element) {
29         AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(parserContext, element);
30     }

AopConfigUtils.java

1     public static void registerAspectJAutoProxyCreatorIfNecessary(
2             ParserContext parserContext, Element sourceElement) {
3        // 在這裏註冊的是AspectJAwareAdvisorAutoProxyCreator
4         BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAutoProxyCreatorIfNecessary(
5                 parserContext.getRegistry(), parserContext.extractSource(sourceElement));
6         useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
7         registerComponentIfNecessary(beanDefinition, parserContext); // 註冊組件 8     }
1     @Nullable
2     public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(
3             BeanDefinitionRegistry registry, @Nullable Object source) {
4 
5         return registerOrEscalateApcAsRequired(AspectJAwareAdvisorAutoProxyCreator.class, registry, source);
6     }

  AspectJAwareAdvisorAutoProxyCreator 實現了 BeanPostProcessor 等上面介紹的接口,主要做用於Bean初始化先後,實例化先後,全部的Bean都被做用到。InstantiationAwareBeanPostProcessor 是 BeanPostProcessor的子接口,但它的調用時間點發生在Bean實例化前,在真正調用doCreateBean()建立bean實例以前執行postProcessBeforeInstantiation()。

AbstractAutoProxyCreator.java

 1     @Override
 2     public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
 3         Object cacheKey = getCacheKey(beanClass, beanName);  // 獲得一個緩存的惟一key(根據beanClass和beanName生成惟一key)  4      // 若是當前targetSourcedBeans(經過自定義TargetSourceCreator建立的TargetSource)不包含cacheKey
 5         if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
 6             if (this.advisedBeans.containsKey(cacheKey)) {  //advisedBeans(已經被加強的Bean,即AOP代理對象)中包含當前cacheKey,返回null,即走Spring默認流程  7                 return null;
 8             }
 9             if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {// 若是是基礎設施類(如Advisor、Advice、AopInfrastructureBean的實現)不進行處理;(略) 10                 this.advisedBeans.put(cacheKey, Boolean.FALSE);
11                 return null;
12             }
13         }
14 
15         // 若是有自定義的TargetSource,在此處建立代理
16         // 禁止目標Bean的沒必要要的默認實例化:
17         // TargetSource將以自定義方式處理目標實例。
18         TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
19         if (targetSource != null) {
20             if (StringUtils.hasLength(beanName)) {
21                 this.targetSourcedBeans.add(beanName);
22             }
23             Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
24             Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
25             this.proxyTypes.put(cacheKey, proxy.getClass());
26             return proxy;
27         }
28 
29         return null;
30     }

經過 AbstractAutoProxyCreator 中的 postProcessAfterInitialization() 建立AOP代理。

 1     @Override
 2     public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
 3         if (bean != null) {
 4             Object cacheKey = getCacheKey(bean.getClass(), beanName);
 5             if (!this.earlyProxyReferences.contains(cacheKey)) {  // 若是以前調用過getEarlyBeanReference獲取包裝目標對象到AOP代理對象(若是須要),則再也不執行  6                 return wrapIfNecessary(bean, beanName, cacheKey);  // 包裝目標對象到AOP代理對象(若是須要)  7             }
 8         }
 9         return bean;
10     }
11     
12     protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
13         if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { // 經過TargetSourceCreator進行自定義TargetSource不須要包裝 14             return bean;
15         }
16         if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {  // 不該該被加強對象不須要包裝 17             return bean;
18         }
19         if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { // 基礎設施或應該skip的不須要保證 20             this.advisedBeans.put(cacheKey, Boolean.FALSE);
21             return bean;
22         }
23 
24         // 若是有advise則建立代理。
25         Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
26         if (specificInterceptors != DO_NOT_PROXY) {
27             this.advisedBeans.put(cacheKey, Boolean.TRUE);
28             Object proxy = createProxy(
29                     bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); // 建立代理對象 30             this.proxyTypes.put(cacheKey, proxy.getClass());
31             return proxy;
32         }
33 
34         this.advisedBeans.put(cacheKey, Boolean.FALSE);
35         return bean;
36     }

參考:

Spring內部的BeanPostProcessor接口總結

【Spring源碼分析】AOP源碼解析(下篇)

相關文章
相關標籤/搜索