spring-aop 4.攔截器鏈的執(zhí)行過程

1.簡介

本篇文章是 AOP 源碼分析系列文章的最后一篇文章,在前面的兩篇文章中,我分別介紹了 Spring AOP 是如何為目標(biāo) bean 篩選合適的通知器,以及如何創(chuàng)建代理對象的過程?,F(xiàn)在我們的得到了 bean 的代理對象,且通知也以合適的方式插在了目標(biāo)方法的前后。接下來要做的事情,就是執(zhí)行通知邏輯了。通知可能在目標(biāo)方法前執(zhí)行,也可能在目標(biāo)方法后執(zhí)行。具體的執(zhí)行時機,取決于用戶的配置。當(dāng)目標(biāo)方法被多個通知匹配到時,Spring 通過引入攔截器鏈來保證每個通知的正常執(zhí)行。在本文中,我們將會通過源碼了解到 Spring 是如何支持 expose-proxy 屬性的,以及通知與攔截器之間的關(guān)系,攔截器鏈的執(zhí)行過程等。和上一篇一樣,在進行源碼分析前,我們先來了解一些背景知識。好了,下面進入正題吧。

2.背景

關(guān)于 expose-proxy,我們先來說說它有什么用,然后再來說說怎么用。Spring 引入 expose-proxy 特性是為了解決目標(biāo)方法調(diào)用同對象中其他方法時,其他方法的切面邏輯無法執(zhí)行的問題。這個解釋可能不好理解,不直觀。那下面我來演示一下它的用法,大家就知道是怎么回事了。我們先來看看 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 /> 標(biāo)簽上。在使用 expose-proxy 時,需要對內(nèi)部調(diào)用進行改造,比如:

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()方法調(diào)用了同類中的另一個方法hello(String),此時hello(String)上的切面邏輯就無法執(zhí)行了。這里,我們要對hello()方法進行改造,強制它調(diào)用代理對象中的hello(String)。改造結(jié)果如下:

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()用于獲取當(dāng)前的代理對象。當(dāng) expose-proxy 被配置為 true 時,該代理對象會被放入 ThreadLocal 中。關(guān)于 expose-proxy,這里先說這么多,后面分析源碼時會再次提及。

3.源碼

本章所分析的源碼來自 JdkDynamicAopProxy,至于 CglibAopProxy 中的源碼,大家若有興趣可以自己去看一下。

3.1JDK 動態(tài)代理邏輯分析

本節(jié),我來分析一下 JDK 動態(tài)代理邏輯。對于 JDK 動態(tài)代理,代理邏輯封裝在 InvocationHandler 接口實現(xiàn)類的 invoke 方法中。JdkDynamicAopProxy 實現(xiàn)了 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 中設(shè)置代理對象
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }

        // 獲取適合當(dāng)前方法的攔截器
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

        // 如果攔截器鏈為空,則直接執(zhí)行目標(biāo)方法
        if (chain.isEmpty()) {
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            // 通過反射執(zhí)行目標(biāo)方法
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        }
        else {
            // 創(chuàng)建一個方法調(diào)用器,并將攔截器鏈傳入其中
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // 執(zhí)行攔截器鏈
            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;
        }
        // 如果返回值類型為基礎(chǔ)類型,比如 int,long 等,當(dāng)返回值為 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);
        }
    }
}

如上,上面的代碼我做了比較詳細的注釋。下面我們來總結(jié)一下 invoke 方法的執(zhí)行流程,如下:

1.檢測 expose-proxy 是否為 true,若為 true,則暴露代理對象
2.獲取適合當(dāng)前方法的攔截器
3.如果攔截器鏈為空,則直接通過反射執(zhí)行目標(biāo)方法
4.若攔截器鏈不為空,則創(chuàng)建方法調(diào)用 ReflectiveMethodInvocation 對象
5.調(diào)用 ReflectiveMethodInvocation 對象的 proceed() 方法啟動攔截器鏈
處理返回值,并返回該值
在以上6步中,我們重點關(guān)注第2步和第5步中的邏輯。第2步用于獲取攔截器鏈,第5步則是啟動攔截器鏈。下面先來分析獲取攔截器鏈的過程。

3.2獲取所有的攔截器

所謂的攔截器,顧名思義,是指用于對目標(biāo)方法的調(diào)用進行攔截的一種工具。攔截器的源碼比較簡單,所以我們直接看源碼好了。下面以前置通知攔截器為例,如下:

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 {
        // 執(zhí)行前置通知邏輯
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        // 通過 MethodInvocation 調(diào)用下一個攔截器,若所有攔截器均執(zhí)行完,則調(diào)用目標(biāo)方法
        return mi.proceed();
    }
}

如上,前置通知的邏輯在目標(biāo)方法執(zhí)行前被執(zhí)行。這里先簡單向大家介紹一下攔截器是什么,關(guān)于攔截器更多的描述將放在下一節(jié)中。本節(jié)我們先來看看如何如何獲取攔截器,如下:

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;
            /*
             * 調(diào)用 ClassFilter 對 bean 類型進行匹配,無法匹配則說明當(dāng)前通知器
             * 不適合應(yīng)用在當(dāng)前 bean 上
             */
            if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
                // 將 advisor 中的 advice 轉(zhuǎn)成相應(yīng)的攔截器
                MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                // 通過方法匹配器對目標(biāo)方法進行匹配
                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 就實現(xiàn)了 MethodInterceptor 接口
     */
    if (advice instanceof MethodInterceptor) {
        interceptors.add((MethodInterceptor) advice);
    }

    /*
     * 對于 AspectJMethodBeforeAdvice 等類型的通知,由于沒有實現(xiàn) MethodInterceptor 
     * 接口,所以這里需要通過適配器進行轉(zhuǎn)換
     */ 
    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()]);
}

以上就是獲取攔截器的過程,代碼有點長,不過好在邏輯不是很復(fù)雜。這里簡單總結(jié)一下以上源碼的執(zhí)行過程,如下:

從緩存中獲取當(dāng)前方法的攔截器鏈
若緩存未命中,則調(diào)用 getInterceptorsAndDynamicInterceptionAdvice 獲取攔截器鏈
遍歷通知器列表
對于 PointcutAdvisor 類型的通知器,這里要調(diào)用通知器所持有的切點(Pointcut)對類和方法進行匹配,匹配成功說明應(yīng)向當(dāng)前方法織入通知邏輯
調(diào)用 getInterceptors 方法對非 MethodInterceptor 類型的通知進行轉(zhuǎn)換
返回攔截器數(shù)組,并在隨后存入緩存中
這里需要說明一下,部分通知器是沒有實現(xiàn) MethodInterceptor 接口的,比如 AspectJMethodBeforeAdvice。我們可以看一下前置通知適配器是如何將前置通知轉(zhuǎn)為攔截器的,如下

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();
        // 創(chuàng)建 MethodBeforeAdviceInterceptor 攔截器
        return new MethodBeforeAdviceInterceptor(advice);
    }
}

如上,適配器的邏輯比較簡單,這里就不多說了。

現(xiàn)在我們已經(jīng)獲得了攔截器鏈,那接下來要做的事情就是啟動攔截器了。所以接下來,我們一起去看看 Spring 是如何讓攔截器鏈運行起來的。

3.3啟動攔截器鏈

3.3.1啟動攔截器

本節(jié)的開始,我們先來說說 ReflectiveMethodInvocation。ReflectiveMethodInvocation 貫穿于攔截器鏈執(zhí)行的始終,可以說是核心。該類的 proceed 方法用于啟動啟動攔截器鏈,下面我們?nèi)タ纯催@個方法的邏輯。

public class ReflectiveMethodInvocation implements ProxyMethodInvocation {

    private int currentInterceptorIndex = -1;

    public Object proceed() throws Throwable {
        // 攔截器鏈中的最后一個攔截器執(zhí)行完后,即可執(zhí)行目標(biāo)方法
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            // 執(zhí)行目標(biāo)方法
            return invokeJoinpoint();
        }

        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            InterceptorAndDynamicMethodMatcher dm =
                    (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            /*
             * 調(diào)用具有三個參數(shù)(3-args)的 matches 方法動態(tài)匹配目標(biāo)方法,
             * 兩個參數(shù)(2-args)的 matches 方法用于靜態(tài)匹配
             */
            if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
                // 調(diào)用攔截器邏輯
                return dm.interceptor.invoke(this);
            }
            else {
                // 如果匹配失敗,則忽略當(dāng)前的攔截器
                return proceed();
            }
        }
        else {
            // 調(diào)用攔截器邏輯,并傳遞 ReflectiveMethodInvocation 對象
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }
}

如上,proceed 根據(jù) currentInterceptorIndex 來確定當(dāng)前應(yīng)執(zhí)行哪個攔截器,并在調(diào)用攔截器的 invoke 方法時,將自己作為參數(shù)傳給該方法。
前置攔截器

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
    private MethodBeforeAdvice advice;
    /**
     * Create a new MethodBeforeAdviceInterceptor for the given advice.
     * @param advice the MethodBeforeAdvice to wrap
     */
    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());
        return mi.proceed();
    }
}

返回攔截器

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
    private final AfterReturningAdvice advice;
    /**
     * Create a new AfterReturningAdviceInterceptor for the given advice.
     * @param advice the AfterReturningAdvice to wrap
     */
    public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {
        Assert.notNull(advice, "Advice must not be null");
        this.advice = advice;
    }

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object retVal = mi.proceed();
        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }

}

后置攔截器

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 {
            // 調(diào)用 proceed
            return mi.proceed();
        }
        finally {
            // 調(diào)用后置通知邏輯
            invokeAdviceMethod(getJoinPointMatch(), null, null);
        }
    }

    //...
}

異常攔截器

public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice
        implements MethodInterceptor, AfterAdvice, Serializable {

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

        super(aspectJBeforeAdviceMethod, pointcut, aif);
    }
    @Override
    public boolean isBeforeAdvice() {
        return false;
    }

    @Override
    public boolean isAfterAdvice() {
        return true;
    }

    @Override
    public void setThrowingName(String name) {
        setThrowingNameNoCheck(name);
    }

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();
        }
        catch (Throwable ex) {
            if (shouldInvokeOnThrowing(ex)) {
                invokeAdviceMethod(getJoinPointMatch(), null, ex);
            }
            throw ex;
        }
    }
    /**
     * In AspectJ semantics, after throwing advice that specifies a throwing clause
     * is only invoked if the thrown exception is a subtype of the given throwing type.
     */
    private boolean shouldInvokeOnThrowing(Throwable ex) {
        return getDiscoveredThrowingType().isAssignableFrom(ex.getClass());
    }
}

環(huán)繞攔截器

public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor, Serializable {

    public AspectJAroundAdvice(
            Method aspectJAroundAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

        super(aspectJAroundAdviceMethod, pointcut, aif);
    }


    @Override
    public boolean isBeforeAdvice() {
        return false;
    }

    @Override
    public boolean isAfterAdvice() {
        return false;
    }

    @Override
    protected boolean supportsProceedingJoinPoint() {
        return true;
    }

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        if (!(mi instanceof ProxyMethodInvocation)) {
            throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
        }
        ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
        ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
        JoinPointMatch jpm = getJoinPointMatch(pmi);
        return invokeAdviceMethod(pjp, jpm, null, null);
    }

    /**
     * Return the ProceedingJoinPoint for the current invocation,
     * instantiating it lazily if it hasn't been bound to the thread already.
     * @param rmi the current Spring AOP ReflectiveMethodInvocation,
     * which we'll use for attribute binding
     * @return the ProceedingJoinPoint to make available to advice methods
     */
    protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) {
        return new MethodInvocationProceedingJoinPoint(rmi);
    }
}

所有的攔截器都在查找的順序按照優(yōu)先級排好了序,調(diào)用鏈的入口是JdkDynamicAopProxy.invoke()方法,目標(biāo)方法的執(zhí)行是在ReflectiveMethodInvocation中的currentInterceptorIndex達到最大長度時返回。如圖:
。。。。待定???

3.3.2

與前面的大部頭相比,本節(jié)的源碼比較短,也很簡單。本節(jié)我們來看一下目標(biāo)方法的執(zhí)行過程,如下:

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);
            // 通過反射執(zhí)行目標(biāo)方法
            return method.invoke(target, args);
        }
        catch (InvocationTargetException ex) {...}
        catch (IllegalArgumentException ex) {...}
        catch (IllegalAccessException ex) {...}
    }
}

4.總結(jié)

到此,本篇文章的就要結(jié)束了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容