1. 程式人生 > 實用技巧 >Spring AOP 原始碼分析 - 攔截器鏈的執行過程

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 {

    @Override
    public void hello() {
        System.out.println("hello");
        this.hello("world");
    }

    @Override
    public void hello(String hello) {
        System.out.println("hello " +  hello);
    }
}

hello()方法呼叫了同類中的另一個方法hello(String),此時hello(String)上的切面邏輯就無法執行了。這裡,我們要對hello()方法進行改造,強制它呼叫代理物件中的hello(String)。改造結果如下:

public class Hello implements IHello {

    @Override
    public void hello() {
        System.out.println("hello");
        ((IHello) AopContext.currentProxy()).hello("world");
    }

    @Override
    public 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 方法的執行流程,如下:

  1. 檢測 expose-proxy 是否為 true,若為 true,則暴露代理物件
  2. 獲取適合當前方法的攔截器
  3. 如果攔截器鏈為空,則直接通過反射執行目標方法
  4. 若攔截器鏈不為空,則建立方法呼叫 ReflectiveMethodInvocation 物件
  5. 呼叫 ReflectiveMethodInvocation 物件的 proceed() 方法啟動攔截器鏈
  6. 處理返回值,並返回該值

在以上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;
    }

    @Override
    public 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()]);
}

以上就是獲取攔截器的過程,程式碼有點長,不過好在邏輯不是很複雜。這裡簡單總結一下以上原始碼的執行過程,如下:

  1. 從快取中獲取當前方法的攔截器鏈
  2. 若快取未命中,則呼叫 getInterceptorsAndDynamicInterceptionAdvice 獲取攔截器鏈
  3. 遍歷通知器列表
  4. 對於 PointcutAdvisor 型別的通知器,這裡要呼叫通知器所持有的切點(Pointcut)對類和方法進行匹配,匹配成功說明應向當前方法織入通知邏輯
  5. 呼叫 getInterceptors 方法對非 MethodInterceptor 型別的通知進行轉換
  6. 返回攔截器陣列,並在隨後存入快取中

這裡需要說明一下,部分通知器是沒有實現 MethodInterceptor 介面的,比如 AspectJMethodBeforeAdvice。我們可以看一下前置通知介面卡是如何將前置通知轉為攔截器的,如下:

class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {

    @Override
    public boolean supportsAdvice(Advice advice) {
        return (advice instanceof MethodBeforeAdvice);
    }

    @Override
    public 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 AbstractAspectJAdvice
        implements MethodInterceptor, AfterAdvice, Serializable {

    public AspectJAfterAdvice(
            Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

        super(aspectJBeforeAdviceMethod, pointcut, aif);
    }


    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            // 呼叫 proceed
            return 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.ADVISOR
            advisors.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) {
        @Override
        public 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() {
    }

    @Override
    public 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 原始碼分析文章列表

Ⅰ. 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 原理探祕 - 容器的建立過程