javascript
Spring AOP 源码分析 - 拦截器链的执行过程
1.簡介
本篇文章是 AOP 源碼分析系列文章的最后一篇文章,在前面的兩篇文章中,我分別介紹了 Spring AOP 是如何為目標 bean 篩選合適的通知器,以及如何創建代理對象的過程。現在我們的得到了 bean 的代理對象,且通知也以合適的方式插在了目標方法的前后。接下來要做的事情,就是執行通知邏輯了。通知可能在目標方法前執行,也可能在目標方法后執行。具體的執行時機,取決于用戶的配置。當目標方法被多個通知匹配到時,Spring 通過引入攔截器鏈來保證每個通知的正常執行。在本文中,我們將會通過源碼了解到 Spring 是如何支持 expose-proxy 屬性的,以及通知與攔截器之間的關系,攔截器鏈的執行過程等。和上一篇文章一樣,在進行源碼分析前,我們先來了解一些背景知識。好了,下面進入正題吧。
2.背景知識
關于 expose-proxy,我們先來說說它有什么用,然后再來說說怎么用。Spring 引入 expose-proxy 特性是為了解決目標方法調用同對象中其他方法時,其他方法的切面邏輯無法執行的問題。這個解釋可能不好理解,不直觀。那下面我來演示一下它的用法,大家就知道是怎么回事了。我們先來看看 expose-proxy 是怎樣配置的,如下:
<bean id="hello" class="xyz.coolblog.aop.Hello"/> <bean id="aopCode" class="xyz.coolblog.aop.AopCode"/><aop:aspectj-autoproxy expose-proxy="true" /><aop:config expose-proxy="true"><aop:aspect id="myaspect" ref="aopCode"><aop:pointcut id="helloPointcut" expression="execution(* xyz.coolblog.aop.*.hello*(..))" /><aop:before method="before" pointcut-ref="helloPointcut" /></aop:aspect> </aop:config>如上,expose-proxy 可配置在 <aop:config/> 和 <aop:aspectj-autoproxy /> 標簽上。在使用 expose-proxy 時,需要對內部調用進行改造,比如:
public class Hello implements IHello {@Overridepublic void hello() {System.out.println("hello");this.hello("world");}@Overridepublic void hello(String hello) {System.out.println("hello " + hello);} }hello()方法調用了同類中的另一個方法hello(String),此時hello(String)上的切面邏輯就無法執行了。這里,我們要對hello()方法進行改造,強制它調用代理對象中的hello(String)。改造結果如下:
public class Hello implements IHello {@Overridepublic void hello() {System.out.println("hello");((IHello) AopContext.currentProxy()).hello("world");}@Overridepublic void hello(String hello) {System.out.println("hello " + hello);} }如上,AopContext.currentProxy()用于獲取當前的代理對象。當 expose-proxy 被配置為 true 時,該代理對象會被放入 ThreadLocal 中。關于 expose-proxy,這里先說這么多,后面分析源碼時會再次提及。
3.源碼分析
本章所分析的源碼來自 JdkDynamicAopProxy,至于 CglibAopProxy 中的源碼,大家若有興趣可以自己去看一下。
3.1 JDK 動態代理邏輯分析
本節,我來分析一下 JDK 動態代理邏輯。對于 JDK 動態代理,代理邏輯封裝在 InvocationHandler 接口實現類的 invoke 方法中。JdkDynamicAopProxy 實現了 InvocationHandler 接口,下面我們就來分析一下 JdkDynamicAopProxy 的 invoke 方法。如下:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {MethodInvocation invocation;Object oldProxy = null;boolean setProxyContext = false;TargetSource targetSource = this.advised.targetSource;Class<?> targetClass = null;Object target = null;try {// 省略部分代碼Object retVal;// 如果 expose-proxy 屬性為 true,則暴露代理對象if (this.advised.exposeProxy) {// 向 AopContext 中設置代理對象oldProxy = AopContext.setCurrentProxy(proxy);setProxyContext = true;}// 獲取適合當前方法的攔截器List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);// 如果攔截器鏈為空,則直接執行目標方法if (chain.isEmpty()) {Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);// 通過反射執行目標方法retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);}else {// 創建一個方法調用器,并將攔截器鏈傳入其中invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);// 執行攔截器鏈retVal = invocation.proceed();}// 獲取方法返回值類型Class<?> returnType = method.getReturnType();if (retVal != null && retVal == target &&returnType != Object.class && returnType.isInstance(proxy) &&!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {// 如果方法返回值為 this,即 return this; 則將代理對象 proxy 賦值給 retVal retVal = proxy;}// 如果返回值類型為基礎類型,比如 int,long 等,當返回值為 null,拋出異常else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);}return retVal;}finally {if (target != null && !targetSource.isStatic()) {targetSource.releaseTarget(target);}if (setProxyContext) {AopContext.setCurrentProxy(oldProxy);}} }如上,上面的代碼我做了比較詳細的注釋。下面我們來總結一下 invoke 方法的執行流程,如下:
在以上6步中,我們重點關注第2步和第5步中的邏輯。第2步用于獲取攔截器鏈,第5步則是啟動攔截器鏈。下面先來分析獲取攔截器鏈的過程。
3.2 獲取所有的攔截器
所謂的攔截器,顧名思義,是指用于對目標方法的調用進行攔截的一種工具。攔截器的源碼比較簡單,所以我們直接看源碼好了。下面以前置通知攔截器為例,如下:
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {/** 前置通知 */private MethodBeforeAdvice advice;public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {Assert.notNull(advice, "Advice must not be null");this.advice = advice;}@Overridepublic Object invoke(MethodInvocation mi) throws Throwable {// 執行前置通知邏輯this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());// 通過 MethodInvocation 調用下一個攔截器,若所有攔截器均執行完,則調用目標方法return mi.proceed();} }如上,前置通知的邏輯在目標方法執行前被執行。這里先簡單向大家介紹一下攔截器是什么,關于攔截器更多的描述將放在下一節中。本節我們先來看看如何如何獲取攔截器,如下:
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {MethodCacheKey cacheKey = new MethodCacheKey(method);// 從緩存中獲取List<Object> cached = this.methodCache.get(cacheKey);// 緩存未命中,則進行下一步處理if (cached == null) {// 獲取所有的攔截器cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClass);// 存入緩存this.methodCache.put(cacheKey, cached);}return cached; }public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class<?> targetClass) {List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);// registry 為 DefaultAdvisorAdapterRegistry 類型AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();// 遍歷通知器列表for (Advisor advisor : config.getAdvisors()) {if (advisor instanceof PointcutAdvisor) {PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;/* * 調用 ClassFilter 對 bean 類型進行匹配,無法匹配則說明當前通知器 * 不適合應用在當前 bean 上 */if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {// 將 advisor 中的 advice 轉成相應的攔截器MethodInterceptor[] interceptors = registry.getInterceptors(advisor);MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();// 通過方法匹配器對目標方法進行匹配if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {// 若 isRuntime 返回 true,則表明 MethodMatcher 要在運行時做一些檢測if (mm.isRuntime()) {for (MethodInterceptor interceptor : interceptors) {interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));}}else {interceptorList.addAll(Arrays.asList(interceptors));}}}}else if (advisor instanceof IntroductionAdvisor) {IntroductionAdvisor ia = (IntroductionAdvisor) advisor;// IntroductionAdvisor 類型的通知器,僅需進行類級別的匹配即可if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {Interceptor[] interceptors = registry.getInterceptors(advisor);interceptorList.addAll(Arrays.asList(interceptors));}}else {Interceptor[] interceptors = registry.getInterceptors(advisor);interceptorList.addAll(Arrays.asList(interceptors));}}return interceptorList; }public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {List<MethodInterceptor> interceptors = new ArrayList<MethodInterceptor>(3);Advice advice = advisor.getAdvice();/* * 若 advice 是 MethodInterceptor 類型的,直接添加到 interceptors 中即可。 * 比如 AspectJAfterAdvice 就實現了 MethodInterceptor 接口 */if (advice instanceof MethodInterceptor) {interceptors.add((MethodInterceptor) advice);}/* * 對于 AspectJMethodBeforeAdvice 等類型的通知,由于沒有實現 MethodInterceptor * 接口,所以這里需要通過適配器進行轉換 */ for (AdvisorAdapter adapter : this.adapters) {if (adapter.supportsAdvice(advice)) {interceptors.add(adapter.getInterceptor(advisor));}}if (interceptors.isEmpty()) {throw new UnknownAdviceTypeException(advisor.getAdvice());}return interceptors.toArray(new MethodInterceptor[interceptors.size()]); }以上就是獲取攔截器的過程,代碼有點長,不過好在邏輯不是很復雜。這里簡單總結一下以上源碼的執行過程,如下:
這里需要說明一下,部分通知器是沒有實現 MethodInterceptor 接口的,比如 AspectJMethodBeforeAdvice。我們可以看一下前置通知適配器是如何將前置通知轉為攔截器的,如下:
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {@Overridepublic boolean supportsAdvice(Advice advice) {return (advice instanceof MethodBeforeAdvice);}@Overridepublic MethodInterceptor getInterceptor(Advisor advisor) {MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();// 創建 MethodBeforeAdviceInterceptor 攔截器return new MethodBeforeAdviceInterceptor(advice);} }如上,適配器的邏輯比較簡單,這里就不多說了。
現在我們已經獲得了攔截器鏈,那接下來要做的事情就是啟動攔截器了。所以接下來,我們一起去看看 Sring 是如何讓攔截器鏈運行起來的。
3.3 啟動攔截器鏈
3.3.1 執行攔截器鏈
本節的開始,我們先來說說 ReflectiveMethodInvocation。ReflectiveMethodInvocation 貫穿于攔截器鏈執行的始終,可以說是核心。該類的 proceed 方法用于啟動啟動攔截器鏈,下面我們去看看這個方法的邏輯。
public class ReflectiveMethodInvocation implements ProxyMethodInvocation {private int currentInterceptorIndex = -1;public Object proceed() throws Throwable {// 攔截器鏈中的最后一個攔截器執行完后,即可執行目標方法if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {// 執行目標方法return invokeJoinpoint();}Object interceptorOrInterceptionAdvice =this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {InterceptorAndDynamicMethodMatcher dm =(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;/* * 調用具有三個參數(3-args)的 matches 方法動態匹配目標方法, * 兩個參數(2-args)的 matches 方法用于靜態匹配 */if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {// 調用攔截器邏輯return dm.interceptor.invoke(this);}else {// 如果匹配失敗,則忽略當前的攔截器return proceed();}}else {// 調用攔截器邏輯,并傳遞 ReflectiveMethodInvocation 對象return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);}} }如上,proceed 根據 currentInterceptorIndex 來確定當前應執行哪個攔截器,并在調用攔截器的 invoke 方法時,將自己作為參數傳給該方法。前面的章節中,我們看過了前置攔截器的源碼,這里來看一下后置攔截器源碼。如下:
public class AspectJAfterAdvice extends AbstractAspectJAdviceimplements MethodInterceptor, AfterAdvice, Serializable {public AspectJAfterAdvice(Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {super(aspectJBeforeAdviceMethod, pointcut, aif);}@Overridepublic Object invoke(MethodInvocation mi) throws Throwable {try {// 調用 proceedreturn mi.proceed();}finally {// 調用后置通知邏輯invokeAdviceMethod(getJoinPointMatch(), null, null);}}//... }如上,由于后置通知需要在目標方法返回后執行,所以 AspectJAfterAdvice 先調用 mi.proceed() 執行下一個攔截器邏輯,等下一個攔截器返回后,再執行后置通知邏輯。如果大家不太理解的話,先看個圖。這里假設目標方法 method 在執行前,需要執行兩個前置通知和一個后置通知。下面我們看一下由三個攔截器組成的攔截器鏈是如何執行的,如下:
注:這里用 advice.after() 表示執行后置通知
本節的最后,插播一個攔截器,即 ExposeInvocationInterceptor。為啥要在這里介紹這個攔截器呢,原因是我在Spring AOP 源碼分析 - 篩選合適的通知器一文中,在介紹 extendAdvisors 方法時,有一個點沒有詳細說明。現在大家已經知道攔截器的概念了,就可以把之前沒法詳細說明的地方進行補充說明。這里再貼一下 extendAdvisors 方法的源碼,如下:
protected void extendAdvisors(List<Advisor> candidateAdvisors) {AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors); }public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {if (!advisors.isEmpty()) {// 省略部分代碼if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {// 向通知器列表中添加 ExposeInvocationInterceptor.ADVISORadvisors.add(0, ExposeInvocationInterceptor.ADVISOR);return true;}}return false; }如上,extendAdvisors 所調用的方法會向通知器列表首部添加 ExposeInvocationInterceptor.ADVISOR。現在我們再來看看 ExposeInvocationInterceptor 的源碼,如下:
public class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {public static final ExposeInvocationInterceptor INSTANCE = new ExposeInvocationInterceptor();// 創建 DefaultPointcutAdvisor 匿名對象public static final Advisor ADVISOR = new DefaultPointcutAdvisor(INSTANCE) {@Overridepublic String toString() {return ExposeInvocationInterceptor.class.getName() +".ADVISOR";}};private static final ThreadLocal<MethodInvocation> invocation =new NamedThreadLocal<MethodInvocation>("Current AOP method invocation");public static MethodInvocation currentInvocation() throws IllegalStateException {MethodInvocation mi = invocation.get();if (mi == null)throw new IllegalStateException("No MethodInvocation found: Check that an AOP invocation is in progress, and that the " +"ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " +"advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor!");return mi;}// 私有構造方法private ExposeInvocationInterceptor() {}@Overridepublic Object invoke(MethodInvocation mi) throws Throwable {MethodInvocation oldInvocation = invocation.get();// 將 mi 設置到 ThreadLocal 中invocation.set(mi);try {// 調用下一個攔截器return mi.proceed();}finally {invocation.set(oldInvocation);}}//... }如上,ExposeInvocationInterceptor.ADVISOR 經過 registry.getInterceptors 方法(前面已分析過)處理后,即可得到 ExposeInvocationInterceptor。ExposeInvocationInterceptor 的作用是用于暴露 MethodInvocation 對象到 ThreadLocal 中,其名字也體現出了這一點。如果其他地方需要當前的 MethodInvocation 對象,直接通過調用 currentInvocation 方法取出。至于哪些地方需要 MethodInvocation,這個大家自己去探索吧。最后,建議大家寫點代碼調試一下。我在一開始閱讀代碼時,并沒有注意到 ExposeInvocationInterceptor,而是在調試代碼的過程中才發現的。比如:
好了,關于攔截器鏈的執行過程這里就講完了。下一節,我們來看一下目標方法的執行過程。大家再忍忍,源碼很快分析完了。
3.3.2 執行目標方法
與前面的大部頭相比,本節的源碼比較短,也很簡單。本節我們來看一下目標方法的執行過程,如下:
protected Object invokeJoinpoint() throws Throwable {return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments); }public abstract class AopUtils {public static Object invokeJoinpointUsingReflection(Object target, Method method, Object[] args)throws Throwable {try {ReflectionUtils.makeAccessible(method);// 通過反射執行目標方法return method.invoke(target, args);}catch (InvocationTargetException ex) {...}catch (IllegalArgumentException ex) {...}catch (IllegalAccessException ex) {...}} }目標方法時通過反射執行的,比較簡單的吧。好了,就不多說了,over。
4.總結
到此,本篇文章的就要結束了。本篇文章是Spring AOP 源碼分析系列文章的最后一篇,從閱讀源碼到寫完本系列的4篇文章總共花了約兩周的時間。總的來說還是有點累的,但是也有很大的收獲和成就感,值了。需要說明的是,Spring IOC 和 AOP 部分的源碼我分析的并不是非常詳細,也有很多地方沒弄懂。這一系列的文章,是作為自己工作兩年的一個總結。由于工作時間不長,工作經驗和技術水平目前都還處于入門階段。所以暫時很難把 Spring IOC 和 AOP 模塊的源碼分析的很出彩,這個請見諒。如果大家在閱讀文章的過程中發現了錯誤,可以指出來,也希望多多指教,這里先說說謝謝。
好了,本篇文章到這里就結束了。謝謝大家的閱讀。
參考
- 《Spring 源碼深度解析》- 郝佳
附錄:Spring 源碼分析文章列表
Ⅰ. IOC
| 2018-05-30 | Spring IOC 容器源碼分析系列文章導讀 |
| 2018-06-01 | Spring IOC 容器源碼分析 - 獲取單例 bean |
| 2018-06-04 | Spring IOC 容器源碼分析 - 創建單例 bean 的過程 |
| 2018-06-06 | Spring IOC 容器源碼分析 - 創建原始 bean 對象 |
| 2018-06-08 | Spring IOC 容器源碼分析 - 循環依賴的解決辦法 |
| 2018-06-11 | Spring IOC 容器源碼分析 - 填充屬性到 bean 原始對象 |
| 2018-06-11 | Spring IOC 容器源碼分析 - 余下的初始化工作 |
Ⅱ. AOP
| 2018-06-17 | Spring AOP 源碼分析系列文章導讀 |
| 2018-06-20 | Spring AOP 源碼分析 - 篩選合適的通知器 |
| 2018-06-20 | Spring AOP 源碼分析 - 創建代理對象 |
| 2018-06-22 | Spring AOP 源碼分析 - 攔截器鏈的執行過程 |
Ⅲ. MVC
| 2018-06-29 | Spring MVC 原理探秘 - 一個請求的旅行過程 |
| 2018-06-30 | Spring MVC 原理探秘 - 容器的創建過程 |
本文在知識共享許可協議 4.0 下發布,轉載需在明顯位置處注明出處
作者:coolblog.xyz
本文同步發布在我的個人博客:http://www.coolblog.xyz
本作品采用知識共享署名-非商業性使用-禁止演繹 4.0 國際許可協議進行許可。
總結
以上是生活随笔為你收集整理的Spring AOP 源码分析 - 拦截器链的执行过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 度量.net framework 迁移到
- 下一篇: JS给html控件赋值