createAopProxy() 方法决定了是使用 JDK 还是 Cglib 来做动态代理:

  • 如果目标对象实现了接口,默认情况下会采用 JDK 的动态代理
  • 如果目标对象没有实现了接口,会使用 CGLIB 动态代理

    1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    2. @Override
    3. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    4. if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
    5. Class<?> targetClass = config.getTargetClass();
    6. if (targetClass == null) {
    7. throw new AopConfigException("TargetSource cannot determine target class: " +
    8. "Either an interface or a target is required for proxy creation.");
    9. }
    10. if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
    11. return new JdkDynamicAopProxy(config);
    12. }
    13. return new ObjenesisCglibAopProxy(config);
    14. }
    15. else {
    16. return new JdkDynamicAopProxy(config);
    17. }
    18. }
    19. .......
    20. }

    JdkDynamicAopProxy

    JDK动态代理时候InvocationHandler的实现类为org.springframework.aop.framework.JdkDynamicAopProxy。
    那么代理方法的调用肯定会进入JdkDynamicAopProxy.invoke()方法 ```java 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 {

    1. if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
    2. // The target does not implement the equals(Object) method itself.
    3. return equals(args[0]);
    4. }
    5. else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
    6. // The target does not implement the hashCode() method itself.
    7. return hashCode();
    8. }
    9. else if (method.getDeclaringClass() == DecoratingProxy.class) {
    10. // There is only getDecoratedClass() declared -> dispatch to proxy config.
    11. return AopProxyUtils.ultimateTargetClass(this.advised);
    12. }
    13. else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
    14. method.getDeclaringClass().isAssignableFrom(Advised.class)) {
    15. // Service invocations on ProxyConfig with the proxy config...
    16. return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
    17. }
    18. Object retVal;
    19. if (this.advised.exposeProxy) {
    20. // Make invocation available if necessary.
    21. oldProxy = AopContext.setCurrentProxy(proxy);
    22. setProxyContext = true;
    23. }
    24. // Get as late as possible to minimize the time we "own" the target,
    25. // in case it comes from a pool.
    26. target = targetSource.getTarget(); // 目标对象
    27. Class<?> targetClass = (target != null ? target.getClass() : null); // 目标对象的类型
    28. // Get the interception chain for this method.
    29. // 这里会对方法进行匹配,因为不是目标对象中的所有方法都需要增强
    30. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
    31. // Check whether we have any advice. If we don't, we can fallback on direct
    32. // reflective invocation of the target, and avoid creating a MethodInvocation.
    33. if (chain.isEmpty()) {
    34. // We can skip creating a MethodInvocation: just invoke the target directly
    35. // Note that the final invoker must be an InvokerInterceptor so we know it does
    36. // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
    37. // 没有匹配的切面,直接通过反射调用目标对象的目标方法
    38. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
    39. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
    40. }
    41. else {
    42. // We need to create a method invocation...
    43. MethodInvocation invocation =
    44. new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
    45. // Proceed to the joinpoint through the interceptor chain.
    46. /**
    47. * @see ReflectiveMethodInvocation#proceed()
    48. */
    49. // 这里才是增强的调用,重点,火炬的传递
    50. retVal = invocation.proceed();
    51. }
    52. // Massage return value if necessary.
    53. Class<?> returnType = method.getReturnType();
    54. if (retVal != null && retVal == target &&
    55. returnType != Object.class && returnType.isInstance(proxy) &&
    56. !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
    57. // Special case: it returned "this" and the return type of the method
    58. // is type-compatible. Note that we can't help if the target sets
    59. // a reference to itself in another returned object.
    60. retVal = proxy;
    61. }
    62. else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
    63. throw new AopInvocationException(
    64. "Null return value from advice does not match primitive return type for: " + method);
    65. }
    66. return retVal;

    } finally {

    1. if (target != null && !targetSource.isStatic()) {
    2. // Must have come from TargetSource.
    3. targetSource.releaseTarget(target);
    4. }
    5. if (setProxyContext) {
    6. // Restore old proxy.
    7. AopContext.setCurrentProxy(oldProxy);
    8. }

    } }

  1. <a name="mh22o"></a>
  2. # ReflectiveMethodInvocation
  3. `interceptorsAndDynamicMethodMatchers`中第一个advice为org.springframework.aop.interceptor.ExposeInvocationInterceptor。
  4. ```java
  5. public Object proceed() throws Throwable {
  6. // We start with an index of -1 and increment early.
  7. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
  8. // 执行到最后一个Advice,才会到这里执行目标方法
  9. return invokeJoinpoint();
  10. }
  11. Object interceptorOrInterceptionAdvice =
  12. this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
  13. if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
  14. // Evaluate dynamic method matcher here: static part will already have
  15. // been evaluated and found to match.
  16. // dm.isRuntime()=true的走这
  17. InterceptorAndDynamicMethodMatcher dm =
  18. (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. }
  23. else {
  24. // Dynamic matching failed.
  25. // Skip this interceptor and invoke the next in the chain.
  26. return proceed();
  27. }
  28. }
  29. else {
  30. // It's an interceptor, so we just invoke it: The pointcut will have
  31. // been evaluated statically before this object was constructed.
  32. // 走这
  33. return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
  34. }
  35. }