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

AspectJAwareAdvisorAutoProxyCreator及爲Bean生成代理時機分析html

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

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

  1. AspectJAwareAdvisorAutoProxyCreator是BeanPostProcessor接口的實現類
  2. postProcessBeforeInitialization方法與postProcessAfterInitialization方法實如今父類AbstractAutoProxyCreator
  3. postProcessBeforeInitialization方法是一個空實現
  4. 邏輯代碼在postProcessAfterInitialization方法中

基於以上的分析,將Bean生成代理的時機已經一目瞭然了:在每一個Bean初始化以後,若是須要,調用AspectJAwareAdvisorAutoProxyCreator中的postProcessBeforeInitialization爲Bean生成代理數組

 

代理對象實例化----判斷是否爲<bean>生成代理app

上文分析了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方法:post

 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:ui

 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:this

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進行了層層的調用。

相關文章
相關標籤/搜索