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

五月的倉頡發表於2017-04-30

AspectJAwareAdvisorAutoProxyCreator及為Bean生成代理時機分析

上篇文章說了,org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator這個類是Spring提供給開發者的AOP的核心類,就是AspectJAwareAdvisorAutoProxyCreator完成了【類/介面-->代理】的轉換過程,首先我們看一下AspectJAwareAdvisorAutoProxyCreator的層次結構:

這裡最值得注意的一點是最左下角的那個方框,我用幾句話總結一下:

  1. AspectJAwareAdvisorAutoProxyCreator是BeanPostProcessor介面的實現類
  2. postProcessBeforeInitialization方法與postProcessAfterInitialization方法實現在父類AbstractAutoProxyCreator
  3. postProcessBeforeInitialization方法是一個空實現
  4. 邏輯程式碼在postProcessAfterInitialization方法中

基於以上的分析,將Bean生成代理的時機已經一目瞭然了:在每個Bean初始化之後,如果需要,呼叫AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization為Bean生成代理

 

代理物件例項化----判斷是否為<bean>生成代理

上文分析了Bean生成代理的時機是在每個Bean初始化之後,下面把程式碼定位到Bean初始化之後,先是AbstractAutowireCapableBeanFactory的initializeBean方法進行初始化:

 1 protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
 2     if (System.getSecurityManager() != null) {
 3         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 4             public Object run() {
 5                 invokeAwareMethods(beanName, bean);
 6                 return null;
 7             }
 8         }, getAccessControlContext());
 9     }
10     else {
11         invokeAwareMethods(beanName, bean);
12     }
13     
14     Object wrappedBean = bean;
15     if (mbd == null || !mbd.isSynthetic()) {
16         wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
17     }
18 
19     try {
20     invokeInitMethods(beanName, wrappedBean, mbd);
21     }
22     catch (Throwable ex) {
23         throw new BeanCreationException(
24                 (mbd != null ? mbd.getResourceDescription() : null),
25                 beanName, "Invocation of init method failed", ex);
26     }
27 
28     if (mbd == null || !mbd.isSynthetic()) {
29         wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
30     }
31     return wrappedBean;
32 }

初始化之前是第16行的applyBeanPostProcessorsBeforeInitialization方法,初始化之後即29行的applyBeanPostProcessorsAfterInitialization方法:

 1 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
 2         throws BeansException {
 3 
 4     Object result = existingBean;
 5     for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
 6         result = beanProcessor.postProcessAfterInitialization(result, beanName);
 7         if (result == null) {
 8             return result;
 9         }
10     }
11     return result;
12 }

這裡呼叫每個BeanPostProcessor的postProcessBeforeInitialization方法。按照之前的分析,看一下AbstractAutoProxyCreator的postProcessAfterInitialization方法實現:

1 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
2     if (bean != null) {
3         Object cacheKey = getCacheKey(bean.getClass(), beanName);
4         if (!this.earlyProxyReferences.contains(cacheKey)) {
5             return wrapIfNecessary(bean, beanName, cacheKey);
6         }
7     }
8     return bean;
9 }

跟一下第5行的方法wrapIfNecessary:

 1 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
 2     if (this.targetSourcedBeans.contains(beanName)) {
 3         return bean;
 4     }
 5     if (this.nonAdvisedBeans.contains(cacheKey)) {
 6         return bean;
 7     }
 8     if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
 9         this.nonAdvisedBeans.add(cacheKey);
10         return bean;
11     }
12 
13     // Create proxy if we have advice.
14     Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
15     if (specificInterceptors != DO_NOT_PROXY) {
16         this.advisedBeans.add(cacheKey);
17         Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
18         this.proxyTypes.put(cacheKey, proxy.getClass());
19         return proxy;
20     }
21 
22     this.nonAdvisedBeans.add(cacheKey);
23     return bean;
24 }

第2行~第11行是一些不需要生成代理的場景判斷,這裡略過。首先我們要思考的第一個問題是:哪些目標物件需要生成代理因為配置檔案裡面有很多Bean,肯定不能對每個Bean都生成代理,因此需要一套規則判斷Bean是不是需要生成代理,這套規則就是第14行的程式碼getAdvicesAndAdvisorsForBean:

1 protected List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) {
2     List<Advisor> candidateAdvisors = findCandidateAdvisors();
3     List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
4     extendAdvisors(eligibleAdvisors);
5     if (!eligibleAdvisors.isEmpty()) {
6         eligibleAdvisors = sortAdvisors(eligibleAdvisors);
7     }
8     return eligibleAdvisors;
9 }

顧名思義,方法的意思是為指定class尋找合適的Advisor。

第2行程式碼,尋找候選Advisors,根據上文的配置檔案,有兩個候選Advisor,分別是<aop:aspect>節點下的<aop:before>和<aop:after>這兩個,這兩個在XML解析的時候已經被轉換生成了RootBeanDefinition。

跳過第3行的程式碼,先看下第4行的程式碼extendAdvisors方法,之後再重點看一下第3行的程式碼。第4行的程式碼extendAdvisors方法作用是向候選Advisor鏈的開頭(也就是List.get(0)的位置)新增一個org.springframework.aop.support.DefaultPointcutAdvisor

第3行程式碼,根據候選Advisors,尋找可以使用的Advisor,跟一下方法實現:

 1 public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
 2     if (candidateAdvisors.isEmpty()) {
 3         return candidateAdvisors;
 4     }
 5     List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();
 6     for (Advisor candidate : candidateAdvisors) {
 7         if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
 8             eligibleAdvisors.add(candidate);
 9         }
10     }
11     boolean hasIntroductions = !eligibleAdvisors.isEmpty();
12     for (Advisor candidate : candidateAdvisors) {
13         if (candidate instanceof IntroductionAdvisor) {
14             // already processed
15             continue;
16         }
17         if (canApply(candidate, clazz, hasIntroductions)) {
18             eligibleAdvisors.add(candidate);
19         }
20     }
21     return eligibleAdvisors;
22 }

整個方法的主要判斷都圍繞canApply展開方法:

 1 public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
 2     if (advisor instanceof IntroductionAdvisor) {
 3         return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
 4     }
 5     else if (advisor instanceof PointcutAdvisor) {
 6         PointcutAdvisor pca = (PointcutAdvisor) advisor;
 7         return canApply(pca.getPointcut(), targetClass, hasIntroductions);
 8     }
 9     else {
10         // It doesn't have a pointcut so we assume it applies.
11         return true;
12     }
13 }

第一個引數advisor的實際型別是AspectJPointcutAdvisor,它是PointcutAdvisor的子類,因此執行第7行的方法:

 1 public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
 2     if (!pc.getClassFilter().matches(targetClass)) {
 3         return false;
 4     }
 5 
 6     MethodMatcher methodMatcher = pc.getMethodMatcher();
 7     IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
 8     if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
 9         introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
10     }
11 
12     Set<Class> classes = new HashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
13     classes.add(targetClass);
14     for (Class<?> clazz : classes) {
15         Method[] methods = clazz.getMethods();
16         for (Method method : methods) {
17             if ((introductionAwareMethodMatcher != null &&
18                 introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
19                     methodMatcher.matches(method, targetClass)) {
20                 return true;
21             }
22         }
23     }
24     return false;
25 }

這個方法其實就是拿當前Advisor對應的expression做了兩層判斷:

  1. 目標類必須滿足expression的匹配規則
  2. 目標類中的方法必須滿足expression的匹配規則,當然這裡方法不是全部需要滿足expression的匹配規則,有一個方法滿足即可

如果以上兩條都滿足,那麼容器則會判斷該<bean>滿足條件,需要被生成代理物件,具體方式為返回一個陣列物件,該陣列物件中儲存的是<bean>對應的Advisor。

 

代理物件例項化----為<bean>生成代理程式碼上下文梳理

上文分析了為<bean>生成代理的條件,現在就正式看一下Spring上下文是如何為<bean>生成代理的。回到AbstractAutoProxyCreator的wrapIfNecessary方法:

 1 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
 2     if (this.targetSourcedBeans.contains(beanName)) {
 3         return bean;
 4     }
 5     if (this.nonAdvisedBeans.contains(cacheKey)) {
 6         return bean;
 7     }
 8     if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
 9         this.nonAdvisedBeans.add(cacheKey);
10         return bean;
11     }
12 
13     // Create proxy if we have advice.
14     Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
15     if (specificInterceptors != DO_NOT_PROXY) {
16         this.advisedBeans.add(cacheKey);
17         Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
18         this.proxyTypes.put(cacheKey, proxy.getClass());
19         return proxy;
20     }
21 
22     this.nonAdvisedBeans.add(cacheKey);
23     return bean;
24 }

第14行拿到<bean>對應的Advisor陣列,第15行判斷只要Advisor陣列不為空,那麼就會通過第17行的程式碼為<bean>建立代理:

 1 protected Object createProxy(
 2         Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
 3 
 4     ProxyFactory proxyFactory = new ProxyFactory();
 5     // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
 6     proxyFactory.copyFrom(this);
 7 
 8     if (!shouldProxyTargetClass(beanClass, beanName)) {
 9         // Must allow for introductions; can't just set interfaces to
10         // the target's interfaces only.
11         Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader);
12         for (Class<?> targetInterface : targetInterfaces) {
13             proxyFactory.addInterface(targetInterface);
14         }
15     }
16 
17     Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
18     for (Advisor advisor : advisors) {
19         proxyFactory.addAdvisor(advisor);
20     }
21 
22     proxyFactory.setTargetSource(targetSource);
23     customizeProxyFactory(proxyFactory);
24 
25     proxyFactory.setFrozen(this.freezeProxy);
26     if (advisorsPreFiltered()) {
27         proxyFactory.setPreFiltered(true);
28     }
29 
30     return proxyFactory.getProxy(this.proxyClassLoader);
31 }

第4行~第6行new出了一個ProxyFactory,Proxy,顧名思義,代理工廠的意思,提供了簡單的方式使用程式碼獲取和配置AOP代理。

第8行的程式碼做了一個判斷,判斷的內容是<aop:config>這個節點中proxy-target-class="false"或者proxy-target-class不配置,即不使用CGLIB生成代理。如果滿足條件,進判斷,獲取當前Bean實現的所有介面,講這些介面Class物件都新增到ProxyFactory中。

第17行~第28行的程式碼沒什麼看的必要,向ProxyFactory中新增一些引數而已。重點看第30行proxyFactory.getProxy(this.proxyClassLoader)這句:

 1 public Object getProxy(ClassLoader classLoader) {
 2     return createAopProxy().getProxy(classLoader);
 3 }

實現程式碼就一行,但是卻明確告訴我們做了兩件事情:

  1. 建立AopProxy介面實現類
  2. 通過AopProxy介面的實現類的getProxy方法獲取<bean>對應的代理

就從這兩個點出發,分兩部分分析一下。

 

代理物件例項化----建立AopProxy介面實現類

看一下createAopProxy()方法的實現,它位於DefaultAopProxyFactory類中:

1 protected final synchronized AopProxy createAopProxy() {
2     if (!this.active) {
3         activate();
4     }
5     return getAopProxyFactory().createAopProxy(this);
6 }

前面的部分沒什麼必要看,直接進入重點即createAopProxy方法:

 1 public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
 2     if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
 3         Class targetClass = config.getTargetClass();
 4         if (targetClass == null) {
 5             throw new AopConfigException("TargetSource cannot determine target class: " +
 6                     "Either an interface or a target is required for proxy creation.");
 7         }
 8         if (targetClass.isInterface()) {
 9             return new JdkDynamicAopProxy(config);
10         }
11         if (!cglibAvailable) {
12             throw new AopConfigException(
13                     "Cannot proxy target class because CGLIB2 is not available. " +
14                     "Add CGLIB to the class path or specify proxy interfaces.");
15         }
16         return CglibProxyFactory.createCglibProxy(config);
17     }
18     else {
19         return new JdkDynamicAopProxy(config);
20     }
21 }

平時我們說AOP原理三句話就能概括:

  1. 對類生成代理使用CGLIB
  2. 對介面生成代理使用JDK原生的Proxy
  3. 可以通過配置檔案指定對介面使用CGLIB生成代理

這三句話的出處就是createAopProxy方法。看到預設是第19行的程式碼使用JDK自帶的Proxy生成代理,碰到以下三種情況例外:

  1. ProxyConfig的isOptimize方法為true,這表示讓Spring自己去優化而不是使用者指定
  2. ProxyConfig的isProxyTargetClass方法為true,這表示配置了proxy-target-class="true"
  3. ProxyConfig滿足hasNoUserSuppliedProxyInterfaces方法執行結果為true,這表示<bean>物件沒有實現任何介面或者實現的介面是SpringProxy介面

在進入第2行的if判斷之後再根據目標<bean>的型別決定返回哪種AopProxy。簡單總結起來就是:

  1. proxy-target-class沒有配置或者proxy-target-class="false",返回JdkDynamicAopProxy
  2. proxy-target-class="true"或者<bean>物件沒有實現任何介面或者只實現了SpringProxy介面,返回Cglib2AopProxy

當然,不管是JdkDynamicAopProxy還是Cglib2AopProxy,AdvisedSupport都是作為建構函式引數傳入的,裡面儲存了具體的Advisor。

 

代理物件例項化----通過getProxy方法獲取<bean>對應的代理

其實程式碼已經分析到了JdkDynamicAopProxy和Cglib2AopProxy,剩下的就沒什麼好講的了,無非就是看對這兩種方式生成代理的熟悉程度而已。

Cglib2AopProxy生成代理的程式碼就不看了,對Cglib不熟悉的朋友可以看Cglib及其基本使用一文。

JdkDynamicAopProxy生成代理的方式稍微看一下:

1 public Object getProxy(ClassLoader classLoader) {
2     if (logger.isDebugEnabled()) {
3         logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
4     }
5     Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
6     findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
7     return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
8 }

這邊解釋一下第5行和第6行的程式碼,第5行程式碼的作用是拿到所有要代理的介面,第6行程式碼的作用是嘗試尋找這些介面方法裡面有沒有equals方法和hashCode方法,同時都有的話打個標記,尋找結束,equals方法和hashCode方法有特殊處理。

最終通過第7行的Proxy.newProxyInstance方法獲取介面/類對應的代理物件,Proxy是JDK原生支援的生成代理的方式。

 

代理方法呼叫原理

前面已經詳細分析了為介面/類生成代理的原理,生成代理之後就要呼叫方法了,這裡看一下使用JdkDynamicAopProxy呼叫方法的原理。

由於JdkDynamicAopProxy本身實現了InvocationHandler介面,因此具體代理前後處理的邏輯在invoke方法中:

 1 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 2     MethodInvocation invocation;
 3     Object oldProxy = null;
 4     boolean setProxyContext = false;
 5 
 6     TargetSource targetSource = this.advised.targetSource;
 7     Class targetClass = null;
 8     Object target = null;
 9 
10     try {
11         if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
12             // The target does not implement the equals(Object) method itself.
13             return equals(args[0]);
14         }
15         if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
16             // The target does not implement the hashCode() method itself.
17             return hashCode();
18         }
19         if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
20                 method.getDeclaringClass().isAssignableFrom(Advised.class)) {
21             // Service invocations on ProxyConfig with the proxy config...
22             return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
23         }
24 
25         Object retVal;
26 
27         if (this.advised.exposeProxy) {
28             // Make invocation available if necessary.
29             oldProxy = AopContext.setCurrentProxy(proxy);
30             setProxyContext = true;
31         }
32 
33         // May be null. Get as late as possible to minimize the time we "own" the target,
34         // in case it comes from a pool.
35         target = targetSource.getTarget();
36         if (target != null) {
37             targetClass = target.getClass();
38         }
39 
40         // Get the interception chain for this method.
41         List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
42 
43         // Check whether we have any advice. If we don't, we can fallback on direct
44         // reflective invocation of the target, and avoid creating a MethodInvocation.
45         if (chain.isEmpty()) {
46             // We can skip creating a MethodInvocation: just invoke the target directly
47             // Note that the final invoker must be an InvokerInterceptor so we know it does
48             // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
49             retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
50         }
51         else {
52             // We need to create a method invocation...
53             invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
54             // Proceed to the joinpoint through the interceptor chain.
55             retVal = invocation.proceed();
56         }
57 
58         // Massage return value if necessary.
59         if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) &&
60                 !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
61             // Special case: it returned "this" and the return type of the method
62             // is type-compatible. Note that we can't help if the target sets
63             // a reference to itself in another returned object.
64             retVal = proxy;
65         }
66         return retVal;
67     }
68     finally {
69         if (target != null && !targetSource.isStatic()) {
70             // Must have come from TargetSource.
71             targetSource.releaseTarget(target);
72         }
73         if (setProxyContext) {
74             // Restore old proxy.
75             AopContext.setCurrentProxy(oldProxy);
76         }
77     }
78 }

第11行~第18行的程式碼,表示equals方法與hashCode方法即使滿足expression規則,也不會為之產生代理內容,呼叫的是JdkDynamicAopProxy的equals方法與hashCode方法。至於這兩個方法是什麼作用,可以自己檢視一下原始碼。

第19行~第23行的程式碼,表示方法所屬的Class是一個介面並且方法所屬的Class是AdvisedSupport的父類或者父介面,直接通過反射呼叫該方法。

第27行~第30行的程式碼,是用於判斷是否將代理暴露出去的,由<aop:config>標籤中的expose-proxy="true/false"配置。

第41行的程式碼,獲取AdvisedSupport中的所有攔截器和動態攔截器列表,用於攔截方法,具體到我們的實際程式碼,列表中有三個Object,分別是:

  • chain.get(0):ExposeInvocationInterceptor,這是一個預設的攔截器,對應的原Advisor為DefaultPointcutAdvisor
  • chain.get(1):MethodBeforeAdviceInterceptor,用於在實際方法呼叫之前的攔截,對應的原Advisor為AspectJMethodBeforeAdvice
  • chain.get(2):AspectJAfterAdvice,用於在實際方法呼叫之後的處理

第45行~第50行的程式碼,如果攔截器列表為空,很正常,因為某個類/介面下的某個方法可能不滿足expression的匹配規則,因此此時通過反射直接呼叫該方法。

第51行~第56行的程式碼,如果攔截器列表不為空,按照註釋的意思,需要一個ReflectiveMethodInvocation,並通過proceed方法對原方法進行攔截,proceed方法感興趣的朋友可以去看一下,裡面使用到了遞迴的思想對chain中的Object進行了層層的呼叫。

 

相關文章