JdkDynamicAopProxy 实现了 InvocationHandler 接口,所以在创建代理对象的时候传递了 this

    1. // jdk动态代理创建代理对象
    2. return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);

    进入方法调用

    1. @Override
    2. @Nullable
    3. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    4. System.out.println("jdk aop 拦截方法:" + method.getName());
    5. Object oldProxy = null;
    6. boolean setProxyContext = false;
    7. // 代理目标
    8. TargetSource targetSource = this.advised.targetSource;
    9. // 代理目标对象
    10. Object target = null;
    11. try {
    12. if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
    13. // 如何代理接口没有定义equals方法,则调用JdkDynamicAopProxy的重写的equals方法
    14. // The target does not implement the equals(Object) method itself.
    15. return equals(args[0]);
    16. } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
    17. // 同上
    18. // The target does not implement the hashCode() method itself.
    19. return hashCode();
    20. } else if (method.getDeclaringClass() == DecoratingProxy.class) {
    21. // There is only getDecoratedClass() declared -> dispatch to proxy config.
    22. return AopProxyUtils.ultimateTargetClass(this.advised);
    23. } else if (!this.advised.opaque
    24. && method.getDeclaringClass().isInterface()
    25. && method.getDeclaringClass().isAssignableFrom(Advised.class)) {
    26. // Service invocations on ProxyConfig with the proxy config...
    27. /*
    28. opaque:表示代理对象是否可以转换成 Advised 类型,默认为false;
    29. 被代理类是否接口;
    30. 被代理类是否实现了接口Advised; 通常情况下被代理的对象或者接口都不会
    31. */
    32. return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
    33. }
    34. // 返回结果
    35. Object retVal;
    36. // 如果暴露代理的话,放到 currentProxy(ThreadLocal)中
    37. if (this.advised.exposeProxy) {
    38. // Make invocation available if necessary.
    39. oldProxy = AopContext.setCurrentProxy(proxy);
    40. setProxyContext = true;
    41. }
    42. // Get as late as possible to minimize the time we "own" the target,
    43. // in case it comes from a pool.
    44. // 获取代理对象
    45. target = targetSource.getTarget();
    46. // 代理对象的Class对象
    47. Class<?> targetClass = (target != null ? target.getClass() : null);
    48. // Get the interception chain for this method.
    49. // 获取方法拦截的调用链
    50. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
    51. // Check whether we have any advice. If we don't, we can fallback on direct
    52. // reflective invocation of the target, and avoid creating a MethodInvocation.
    53. if (chain.isEmpty()) {
    54. /*
    55. We can skip creating a MethodInvocation: just invoke the target directly
    56. Note that the final invoker must be an InvokerInterceptor so we know it does
    57. nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
    58. */
    59. // 如果没有拦截方法,直接调用目标的方法
    60. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
    61. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
    62. } else {
    63. // 创建MethodInvocation,对方法进行拦截调用
    64. MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
    65. // Proceed to the joinpoint through the interceptor chain.
    66. retVal = invocation.proceed();
    67. }
    68. // Massage return value if necessary.
    69. // 整理返回值
    70. Class<?> returnType = method.getReturnType();
    71. if (retVal != null
    72. && retVal == target
    73. && returnType != Object.class
    74. && returnType.isInstance(proxy)
    75. && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
    76. // Special case: it returned "this" and the return type of the method
    77. // is type-compatible. Note that we can't help if the target sets
    78. // a reference to itself in another returned object.
    79. retVal = proxy;
    80. } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
    81. throw new AopInvocationException("Null return value from advice does not match primitive return type for:
    82. " + method);
    83. }
    84. return retVal;
    85. } finally {
    86. if (target != null && !targetSource.isStatic()) {
    87. // Must have come from TargetSource.
    88. targetSource.releaseTarget(target);
    89. }
    90. if (setProxyContext) {
    91. // Restore old proxy.
    92. AopContext.setCurrentProxy(oldProxy);
    93. }
    94. }
    95. }

    过程:

    1. 首先判断方法是否为 equals 或者 hashcode,如果被代理对象没有实现的话,使用代理对象重写的方法;
    2. 判断如果父类是 DecoratingProxy ,直接调用目标对象;
    3. 判断被代理类是否为接口,是否为Advised或者父接口,是否可以转换成Advised类型,满足的话,直接调用目标方法;
    4. 如果要暴露代理对象的话,将代理配置放到 ThreadLocal 中,实现该线程下共享;
    5. 获取代理对象,获取方法拦截的调用链;
    6. 如果调用链为空,那么直接调用目标方法;
    7. 调用链不为空,创建 MethodInvocation 对象,执行方法的拦截器;(这里用到责任链模式)
    8. 整理最终返回值,返回。

    执行方法拦截在 ReflectiveMethodInvocation 对象中执行,首先看下该类父类关系:image.png

    入口方法 proceed() 由接口 Joinpoint 提供.

    1. package org.aopalliance.intercept;
    2. import java.lang.reflect.AccessibleObject;
    3. public interface Joinpoint {
    4. // 继续进行链中的下一个拦截器。
    5. Object proceed() throws Throwable;
    6. // 被代理对象
    7. Object getThis();
    8. AccessibleObject getStaticPart();
    9. }
    1. @Override
    2. @Nullable
    3. public Object proceed() throws Throwable {
    4. // We start with an index of -1 and increment early.
    5. // 递归出口,判断是否到了最后一个拦截器。调用连接点方法,也就是目标方法
    6. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
    7. return invokeJoinpoint();
    8. }
    9. // 根据顺序获取目标方法的拦截方法
    10. Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    11. if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
    12. // Evaluate dynamic method matcher here: static part will already have been evaluated and found to match.
    13. /*
    14. 动态匹配
    15. 判断拦截器是否匹配目标方法,能拦截那么就拦截执行;
    16. 不行就执行下一个拦截器;
    17. */
    18. InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
    19. Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
    20. if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
    21. return dm.interceptor.invoke(this);
    22. } else {
    23. // Dynamic matching failed.
    24. // Skip this interceptor and invoke the next in the chain.
    25. return proceed();
    26. }
    27. } else {
    28. // It's an interceptor, so we just invoke it: The pointcut will have
    29. // been evaluated statically before this object was constructed.
    30. // 普通的拦截器:
    31. /*
    32. ExposeInvocationInterceptor、DelegatePerTargetObjectIntroductionInterceptor
    33. 、MethodBeforeAdviceInterceptor、AspectJAroundAdvice、AspectJAfterAdvice
    34. */
    35. return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    36. }
    37. }

    这是一个递归方法,递归执行拦截器方法。根据集合下标依次执行。当执行到最后一个拦截器,就是递归的出口,直接执行目标对象方法。

    拿到一个拦截器,判断是否为 InterceptorAndDynamicMethodMatcher (内部框架类,将 MethodInterceptor 实例与 MethodMatcher 组合在一起)
    如果不是的话,那么直接执行拦截器方法,并且带着当前 ReflectiveMethodInvocation 对象;
    我们的拦截方法会被解析成 MethodInterceptor 所以这个分支不会走。
    比如我们的前置增强对应的实例为:org.springframework.aop.aspectj.AspectJMethodBeforeAdvice
    那么就会进入这个拦截器的方法

    1. // 该方法由 MethodInterceptor 提供
    2. @Override
    3. public Object invoke(MethodInvocation mi) throws Throwable {
    4. this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
    5. return mi.proceed();
    6. }

    首先执行增强方法,然后再继续执行拦截链上的下一个拦截方法。