Spring的JDK动态代理如何实现的(源码解析)

2023-06-28 14:31:31 浏览数 (1)

前言

上一篇文章中提到了SpringAOP是如何决断使用哪种动态代理方式的,本文接上文讲解SpringAOP的JDK动态代理是如何实现的。SpringAOP的实现其实也是使用了ProxyInvocationHandler这两个东西的。

JDK动态代理的使用方式

首先对于InvocationHandler的创建是最为核心的,可以自定义类实现它。实现后需要重写3个函数:

  • 构造函数,将代理的对象闯入
  • invoke方法,此方法中实现了AOP增强的所有逻辑
  • getProxy方法,此方法千篇一律,但是必不可少的一步

接下来我们看一下Spring中的JDK代理方式是如何实现的吧。

看源码之前先大致了解一下Spring的JDK创建过程的大致流程

如图:

  • 看源码(JdkDynamicAopProxy.java)
代码语言:javascript复制
/**
     * 代理对象的配置信息,例如保存了 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方法(该方法是一个回调方法)。具体看源码

  • 看源码
代码语言:javascript复制
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)
代码语言:javascript复制
@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,加入到拦截器链中,

  • 看源码
代码语言:javascript复制
@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)
代码语言:javascript复制
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)
代码语言:javascript复制
@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的构造方式进行了赋值,所以我们这里先看一下获取到的所有拦截器的顺序图,

从上面的顺序图中我们看到其顺序是AspectJAfterThrowingAdvice -> AfterReturningAdviceInterceptor -> AspectJAfterAdvice -> MethodBeforeAdviceInterceptor,

因为proceed方法是递归调用的,所以该方法拦截器的执行顺序也是按照上面的顺序执行的。接下来我们先看一下proceed方法中的核心调用dm.interceptor.invoke(this),这里很重要,因为它传入的参数是this,也就是ReflectiveMethodInvocation ,了解这些后我们先看一下AspectJAfterThrowingAdvice这拦截器链中第一个执行的连接器。

  • 看源码(AspectJAfterThrowingAdvice.java)
代码语言:javascript复制
@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的源码

  • 看源码
代码语言:javascript复制
@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)
代码语言:javascript复制
@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方法

  • 看源码
代码语言:javascript复制
@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)
代码语言:javascript复制
@Nullable
protected Object invokeJoinpoint() throws Throwable {
    return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
}

继续追踪invokeJoinpointUsingReflection方法:

  • 看源码(AopUtils.java)
代码语言:javascript复制
@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) { 代码中,也
代码语言:javascript复制
catch (Throwable ex) {
    if (shouldInvokeOnThrowing(ex)) {
        invokeAdviceMethod(getJoinPointMatch(), null, ex);
    }
    throw ex;
}

如果目标bean的method或者前面的增强方法中出现了异常,则会被这里的catch捕获,也是通过反射的方式执行@AfterThrowing注解的方法,然后退栈

总结

这个代理类的调用过程,我们可以看到时一个递归的调用过程,通过ReflectiveMethodInvocationproceed方法递归调用,顺序执行拦截器链中的AspectJAfterThrowingAdvice、AfterReturningAdviceInterceptor、AspectJAfterAdvice、MethodBeforeAdviceInterceptor这几个拦截器,在拦截器中反射调用增强方法。

0 人点赞