Spring的JDK動態代理如何實現的(原始碼解析)

碼上遇見你發表於2021-10-18
前言

上一篇文章中提到了SpringAOP是如何決斷使用哪種動態代理方式的,本文接上文講解SpringAOP的JDK動態代理是如何實現的。SpringAOP的實現其實也是使用了ProxyInvocationHandler這兩個東西的。

JDK動態代理的使用方式

首先對於InvocationHandler的建立是最為核心的,可以自定義類實現它。實現後需要重寫3個函式:

  • 建構函式,將代理的物件闖入
  • invoke方法,此方法中實現了AOP增強的所有邏輯
  • getProxy方法,此方法千篇一律,但是必不可少的一步

接下來我們看一下Spring中的JDK代理方式是如何實現的吧。

看原始碼之前先大致瞭解一下Spring的JDK建立過程的大致流程

如圖:
image

  • 看原始碼(JdkDynamicAopProxy.java)
/**
     * 代理物件的配置資訊,例如儲存了 TargetSource 目標類來源、能夠應用於目標類的所有 Advisor
     */
private final AdvisedSupport advised;
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
    Assert.notNull(config, "AdvisedSupport must not be null");
    // config.getAdvisorCount() == 0 沒有 Advisor,表示沒有任何動作
    if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
        throw new AopConfigException("No advisors and no TargetSource specified");
    }
    this.advised = config;
    // 獲取需要代理的介面(目標類實現的介面,會加上 Spring 內部的幾個介面,例如 SpringProxy
    this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    //判斷目標類是否重寫了 `equals` 或者 `hashCode` 方法
    // 沒有重寫在攔截到這兩個方法的時候,會呼叫當前類的實現
    findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
@Override
    public Object getProxy() {
    return getProxy(ClassUtils.getDefaultClassLoader());
}
@Override
    public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isTraceEnabled()) {
        logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
    }
    // 呼叫 JDK 的 Proxy#newProxyInstance(..) 方法建立代理物件
    // 傳入的引數就是當前 ClassLoader 類載入器、需要代理的介面、InvocationHandler 實現類
    return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
@Override
    @Nullable
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object oldProxy = null;
    Boolean setProxyContext = false;
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;
    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        } else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // There is only getDecoratedClass() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClass(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                            method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
        Object retVal;
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Class<?> targetClass = (target != null ? target.getClass() : null);
        // Get the interception chain for this method.
        // 獲取當前方法的攔截器鏈  具體實現是在 DefaultAdvisorChainFactory
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            //  將攔截器封裝在ReflectiveMethodInvocation,以便於使用其proceed進行連結表用攔截器
            MethodInvocation invocation =
                                    new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // 執行攔截器鏈
            retVal = invocation.proceed();
        }
        // Massage return value if necessary.
        Class<?> returnType = method.getReturnType();
        // 返回結果
        if (retVal != null && retVal == target &&
                            returnType != Object.class && returnType.isInstance(proxy) &&
                            !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        } 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()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}
  • 原始碼分析
    從上面的原始碼可以看出Spring中的JDKDynamicAopProxy和我們自定一JDK代理是一樣的,也是實現了InvocationHandler介面。並且提供了getProxy方法建立代理類,重寫了invoke方法(該方法是一個回撥方法)。具體看原始碼

  • 看原始碼

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object oldProxy = null;
    Boolean setProxyContext = false;
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;
    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        } else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // There is only getDecoratedClass() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClass(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                            method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }
        Object retVal;
        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }
        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Class<?> targetClass = (target != null ? target.getClass() : null);
        // Get the interception chain for this method.
        // 獲取當前方法的攔截器鏈  具體實現是在 DefaultAdvisorChainFactory
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            //  將攔截器封裝在ReflectiveMethodInvocation,以便於使用其proceed進行連結表用攔截器
            MethodInvocation invocation =
                                    new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // 執行攔截器鏈
            retVal = invocation.proceed();
        }
        // Massage return value if necessary.
        Class<?> returnType = method.getReturnType();
        // 返回結果
        if (retVal != null && retVal == target &&
                            returnType != Object.class && returnType.isInstance(proxy) &&
                            !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        } 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()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}
  • 原始碼分析

    首先我們先看一下List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);該方法主要是獲取目標bean中匹配method的增強器,並將增強器封裝成攔截器鏈,具體實現是在DefaultAdvisorChainFactory中。

  • 看原始碼(DefaultAdvisorChainFactory.java)

@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
            Advised config, Method method, @Nullable Class<?> targetClass) {
    // This is somewhat tricky... We have to process introductions first,
    // but we need to preserve order in the ultimate list.
    AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
    Advisor[] advisors = config.getAdvisors();
    List<Object> interceptorList = new ArrayList<>(advisors.length);
    Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
    Boolean hasIntroductions = null;
    // 獲取bean中的所有增強器
    for (Advisor advisor : advisors) {
        if (advisor instanceof PointcutAdvisor) {
            // Add it conditionally.
            PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
            if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
                MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                Boolean match;
                if (mm instanceof IntroductionAwareMethodMatcher) {
                    if (hasIntroductions == null) {
                        hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
                    }
                    match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
                } else {
                    // 根據增強器中的Pointcut判斷增強器是否能匹配當前類中的method
                    // 我們要知道目標Bean中並不是所有的方法都需要增強,也有一些普通方法
                    match = mm.matches(method, actualClass);
                }
                if (match) {
                    // 如果能匹配,就將 advisor 封裝成 MethodInterceptor 加入到 interceptorList 中
                    // 具體實現在 DefaultAdvisorAdapterRegistry
                    MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                    if (mm.isRuntime()) {
                        // Creating a new object instance in the getInterceptors() method
                        // isn't a problem as we normally cache created chains.
                        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;
            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;
}
  • 原始碼分析

    我們知道並不是所有的方法都需要增強,我們在剛剛也有提到,所以我們需要遍歷所有的Advisor,根據Pointcut判斷增強器是否能匹配當前類中的method,取出能匹配的增強器,緊接著檢視MethodInterceptor[] interceptors = registry.getInterceptors(advisor); ,如果能夠匹配了直接封裝成 MethodInterceptor,加入到攔截器鏈中,

  • 看原始碼

@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
    List<MethodInterceptor> interceptors = new ArrayList<>(3);
    Advice advice = advisor.getAdvice();
    if (advice instanceof MethodInterceptor) {
        interceptors.add((MethodInterceptor) advice);
    }
    // 這裡遍歷三個介面卡,將對應的advisor轉化成Interceptor
    // 這三個介面卡分別是 MethodBeforeAdviceAdapter,AfterReturningAdviceAdapter,ThrowsAdviceAdapter
    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[0]);
}
private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
public DefaultAdvisorAdapterRegistry() {
    registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
    registerAdvisorAdapter(new AfterReturningAdviceAdapter());
    registerAdvisorAdapter(new ThrowsAdviceAdapter());
}

原始碼分析

在spring中AspectJAroundAdviceAspectJAfterAdviceAspectJAfterThrowingAdvice這3個增強器都實現了MethodInterceptor介面,AspectJMethodBeforeAdvice AspectJAfterReturningAdvice 並沒有實現 MethodInterceptor 介面;因此這裡Spring這裡採用的是介面卡模式,注意這裡spring採用了介面卡模式AspectJMethodBeforeAdvice AspectJAfterReturningAdvice 轉化成能滿足需求的MethodInterceptor實現

然後遍歷adapters,通過adapter.supportsAdvice(advice)找到advice對應的介面卡,adapter.getInterceptor(advisor)將advisor轉化成對應的interceptor;

有興趣的可以看一下可以自行檢視一下AspectJAroundAdviceAspectJMethodBeforeAdviceAspectJAfterAdviceAspectJAfterReturningAdviceAspectJAfterThrowingAdvice、這幾個增強器。以及MethodBeforeAdviceAdapterAfterReturningAdviceAdapter這兩個介面卡。

經過介面卡模式的操作,我們獲取到了一個攔截器鏈。鏈中包括AspectJAroundAdvice、AspectJAfterAdvice、AspectJAfterThrowingAdvice、MethodBeforeAdviceInterceptor、AfterReturningAdviceInterceptor

終於經過上述的流程,`List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);`這一步完成。獲取到了當前方法的攔截器鏈

我們繼續回到JDKDynamicAopProxy.java類中,完成了當前方法攔截器鏈的獲取,接下來我們檢視MethodInvocation invocation =new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);這一段程式碼。改程式碼的主要作用就是將攔截器封裝在ReflectiveMethodInvocation,以便於使用其proceed進行連結表用攔截器。

  • 看原始碼(ReflectiveMethodInvocation.java)
private int currentInterceptorIndex = -1;
protected ReflectiveMethodInvocation(
            Object proxy, @Nullable Object target, Method method, @Nullable Object[] arguments,
            @Nullable Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
    this.proxy = proxy;
    this.target = target;
    this.targetClass = targetClass;
    this.method = BridgeMethodResolver.findBridgedMethod(method);
    this.arguments = AopProxyUtils.adaptArgumentsIfNecessary(method, arguments);
    this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
}
  • 原始碼分析

    ReflectiveMethodInvocation的構造器做了簡單的賦值、鏈的封裝,不過要注意一下private int currentInterceptorIndex = -1;這行程式碼。這個變數代表的是Interceptor的下標,從-1開始的,Interceptor執行一個,就會走++this.currentInterceptorIndex,看完建構函式,接著看一下proceed方法

  • 看原始碼(ReflectiveMethodInvocation.java)

@Override
@Nullable
public Object proceed() throws Throwable {
    // We start with an index of -1 and increment early.
    /*
        * 首先,判斷是不是所有的interceptor(也可以想像成advisor)都被執行完了。
        *     判斷的方法是看 currentInterceptorIndex 這個變數的值,有沒有增加到Interceptor總個數這個數值
        *     如果到了,就執行被代理方法 invokeJoinpoint();如果沒到,就繼續執行Interceptor。
        * */
    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        return invokeJoinpoint();
    }
    // 如果Interceptor沒有被全部執行完,就取出要執行的Interceptor,並執行
    // currentInterceptorIndex 先自增
    Object interceptorOrInterceptionAdvice =
                    this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    // 如果Interceptor是PointCut型別
    if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
        // Evaluate dynamic method matcher here: static part will already have
        // been evaluated and found to match.
        InterceptorAndDynamicMethodMatcher dm =
                            (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
        Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
        // 如果當前方法符合Interceptor的PointCut限制,就執行Interceptor
        if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
            // 這裡將this當變數傳進去,這是非常重要的一點
            return dm.interceptor.invoke(this);
        }
        // 如果不符合,就跳過當前Interceptor,執行下一個Interceptor else {
            // Dynamic matching failed.
            // Skip this interceptor and invoke the next in the chain.
            return proceed();
        }
    }
    // 如果Interceptor不是PointCut型別,就直接執行Interceptor裡面的增強。 else {
        // It's an interceptor, so we just invoke it: The pointcut will have
        // been evaluated statically before this object was constructed.
        return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    }
}
  • 原始碼分析

分析proceed方法時,首先我們回到JDKDynamicAopProxy的類中檢視一下List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);,這裡獲取了所有的攔截器,然後通過ReflectiveMethodInvocation的構造方式進行了賦值,所以我們這裡先看一下獲取到的所有攔截器的順序圖,
image
從上面的順序圖中我們看到其順序是AspectJAfterThrowingAdvice->AfterReturningAdviceInterceptor->AspectJAfterAdvice->MethodBeforeAdviceInterceptor,

因為proceed方法是遞迴呼叫的,所以該方法攔截器的執行順序也是按照上面的順序執行的。接下來我們先看一下proceed方法中的核心呼叫`dm.interceptor.invoke(this)`,這裡很重要,因為它傳入的引數是`this`,也就是`ReflectiveMethodInvocation`  ,瞭解這些後我們先看一下`AspectJAfterThrowingAdvice`這攔截器鏈中第一個執行的聯結器。
  • 看原始碼(AspectJAfterThrowingAdvice.java)
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        // 直接呼叫MethodInvocation的proceed方法
        // 從proceed()方法中我們知道dm.interceptor.invoke(this)傳過來的引數就是 ReflectiveMethodInvocation 執行器本身
        // 也就是說這裡又直接呼叫了 ReflectiveMethodInvocation 的proceed()方法
        return mi.proceed();
    }
    catch (Throwable ex) {
        if (shouldInvokeOnThrowing(ex)) {
            invokeAdviceMethod(getJoinPointMatch(), null, ex);
        }
        throw ex;
    }
}
  • 原始碼分析

    該類的invoke方法中,注意mi.proceed(),上面我們說到dm.interceptor.invoke(this)傳過來的引數就是ReflectiveMethodInvocation執行器本身,所以mi就是ReflectiveMethodInvocation,也就是說又會執行ReflectiveMethodInvocation的proceed方法,然後使ReflectiveMethodInvocation的變數currentInterceptorIndex自增,緊接著就會獲取攔截器鏈中的下一個攔截器AfterReturningAdviceInterceptor,執行它的invoke方法,此時第一個攔截器的invoke方法就卡在了mi.proceed()這裡;繼續追蹤AfterReturningAdviceInterceptor.java的原始碼

  • 看原始碼

@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
    // 直接呼叫MethodInvocation的proceed方法
    Object retVal = mi.proceed();
    this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
    return retVal;
}
  • 原始碼分析

    和第一個攔截器一樣,它也是呼叫了ReflectiveMethodInvocationproceed方法,此時第二個攔截器也會卡在mi.proceed這裡。並且使ReflectiveMethodInvocation的變數currentInterceptorIndex自增,緊接著又會獲取下一個攔截器AspectJAfterAdvice.java

  • 看原始碼(AspectJAfterAdvice.java)

@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        // 直接呼叫MethodInvocation的proceed方法
        return mi.proceed();
    }
    finally {
        // 啟用增強方法
        invokeAdviceMethod(getJoinPointMatch(), null, null);
    }
}
  • 原始碼分析

    此時這個類的invoke方法也會執行ReflectiveMethodInvocation方法的proceed方法,同樣也使currentInterceptorIndex變數自增,此時第三個攔截器也會卡在mi.proceed方法上,ReflectiveMethodInvocation又去呼叫下一個攔截器MethodBeforeAdviceInterceptor.javainvoke方法

  • 看原始碼

@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
    // 這裡終於開始做事了,呼叫增強器的before方法,明顯是通過反射的方式呼叫
    // 到這裡增強方法before的業務邏輯執行
    this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
    // 又呼叫了呼叫MethodInvocation的proceed方法
    return mi.proceed();
}
  • 原始碼分析

    此時,this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());這裡終於利用反射的方式呼叫了切面裡面增強器的before方法,這時ReflectiveMethodInvocationthis.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1應該為true了,那麼就會執行return invokeJoinpoint();這行程式碼也就是執行bean的目標方法,接下來我們來看看目標方法的執行

  • 看原始碼(ReflectiveMethodInvocation.java)

@Nullable
@Nullable
protected Object invokeJoinpoint() throws Throwable {
    return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
}

繼續追蹤invokeJoinpointUsingReflection方法:

  • 看原始碼(AopUtils.java)
@Nullable
public static Object invokeJoinpointUsingReflection(@Nullable Object target, Method method, Object[] args)
            throws Throwable {
    // Use reflection to invoke the method.
    try {
        ReflectionUtils.makeAccessible(method);
        // 直接通過反射呼叫目標bean中的method
        return method.invoke(target, args);
    }
    catch (InvocationTargetException ex) {
        // Invoked method threw a checked exception.
        // We must rethrow it. The client won't see the interceptor.
        throw ex.getTargetException();
    }
    catch (IllegalArgumentException ex) {
        throw new AopInvocationException("AOP configuration seems to be invalid: tried calling method [" +
                            method + "] on target [" + target + "]", ex);
    }
    catch (IllegalAccessException ex) {
        throw new AopInvocationException("Could not access method [" + method + "]", ex);
    }
}
  • 原始碼分析

before方法執行完後,就通過反射的方式執行目標bean中的method,並且返回了結果。接下來我們繼續想一下程式會怎麼繼續執行呢?

  • MethodBeforeAdviceInterceptor執行完了後,開始退棧,AspectJAfterAdvice中invoke卡在第5行的程式碼繼續往下執行, 我們看到在AspectJAfterAdvice的invoke方法中的finally中第8行有這樣一句話invokeAdviceMethod(getJoinPointMatch(), null, null);這裡就是通過反射呼叫AfterAdvice的方法,意思是切面類中的 @After方法不管怎樣都會執行,因為在finally中。
  • AspectJAfterAdvice中invoke方法發執行完後,也開始退棧,接著就到了AfterReturningAdviceInterceptor的invoke方法的Object retVal = mi.proceed()開始恢復,但是此時如果目標bean和前面增強器中出現了異常,此時AfterReturningAdviceInterceptor中this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis())這一行程式碼就不會執行了,直接退棧;如果沒有出現異常,則執行這一行,也就是通過反射執行切面類中@AfterReturning註解的方法,然後退棧
  • AfterReturningAdviceInterceptor退棧後,就到了AspectJAfterThrowingAdvice攔截器,此攔截器中invoke方法的return mi.proceed();這一行程式碼開始恢復;我們看到在 catch (Throwable ex) { 程式碼中,也
catch (Throwable ex) {
   if (shouldInvokeOnThrowing(ex)) {
       invokeAdviceMethod(getJoinPointMatch(), null, ex);
   }
   throw ex;
}

如果目標bean的method或者前面的增強方法中出現了異常,則會被這裡的catch捕獲,也是通過反射的方式執行@AfterThrowing註解的方法,然後退棧

總結

這個代理類的呼叫過程,我們可以看到時一個遞迴的呼叫過程,通過ReflectiveMethodInvocationproceed方法遞迴呼叫,順序執行攔截器鏈中的AspectJAfterThrowingAdvice、AfterReturningAdviceInterceptor、AspectJAfterAdvice、MethodBeforeAdviceInterceptor這幾個攔截器,在攔截器中反射呼叫增強方法。

微信搜尋【碼上遇見你】獲取更多精彩內容

相關文章