Java 动态代理 Cglib JDK

AOP 代理的两种实现

  • jdk是代理接口,私有方法必然不会存在在接口里,所以就不会被拦截到;
  • cglib是子类,private的方法照样不会出现在子类里,也不能被拦截。

    JDK 动态代理

    具体有如下四步骤:
  1. 通过实现 InvocationHandler 接口创建自己的调用处理器;
  2. 通过为 Proxy 类指定 ClassLoader 对象和一组 interface 来创建动态代理类;
  3. 通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型;
  4. 通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。

    示例

    创建业务接口

    1. public interface UserService {
    2. /**
    3. * 需要增强的方法
    4. */
    5. void add();
    6. }

    创建业务接口 实现类

    1. public class UserServiceImpl implements UserService {
    2. @Override
    3. public void add() {
    4. System.out.println("-------------业务逻辑方法 add ------------");
    5. }
    6. }

    创建自定义的 InvocationHandler,用于对接口提供的方法进行增强

    1. public class MyInvocationHandler implements InvocationHandler {
    2. /**
    3. * 需要增强的对象
    4. */
    5. private Object target;
    6. public MyInvocationHandler(Object target) {
    7. this.target = target;
    8. }
    9. /**
    10. * 执行目标对象
    11. */
    12. @Override
    13. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    14. System.out.println("-------------方法执行前的增强逻辑 ------------");
    15. Object result = method.invoke(target, args);
    16. System.out.println("-------------方法执行后的增强逻辑 ------------");
    17. return result;
    18. }
    19. public Object getProxy() {
    20. return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
    21. }
    22. }

    测试类

    1. public class ProxyTest {
    2. @Test
    3. public void contextTest() {
    4. // 实例化目标对象
    5. UserService userService = new UserServiceImpl();
    6. // 实例化 InvocationHandler
    7. MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);
    8. // 生成代理对象
    9. UserService proxy = (UserService) invocationHandler.getProxy();
    10. // 输出代理类的class
    11. ProxySourceClassUtil.writeClassToDisk("C:\\Users\\Fcant\\Desktop\\" + proxy.getClass().getSimpleName() + ".class", proxy.getClass().getSimpleName(), UserService.class);
    12. // 调用代理对象的方法
    13. proxy.add();
    14. }
    15. }

    输出结果:

    1. Connected to the target VM, address: '127.0.0.1:60738', transport: 'socket'
    2. -------------方法执行前的增强逻辑 ------------
    3. -------------业务逻辑方法 add ------------
    4. -------------方法执行后的增强逻辑 ------------
    5. Disconnected from the target VM, address: '127.0.0.1:60738', transport: 'socket'

    用起来很简单,其实,这基本上就 AOP 的一个简单实现了,在目标对象的方法执行之前和 执行之后进行了增强。Spring的AOP实现其实也是用了 Proxy 和 InvocationHandler。在整个创建过程中InvocationHandler的创建最为核心,在自定义的InvocationHandler中需要重新3个函数:

  5. 构造函数,将代理的对象传入。

  6. invoke方法,此方法中实现了AOP增强的所有逻辑。
  7. getProxy方法,此方千篇一律,但是必不可少。

    反编译代理类结果

    1. package com.fcant.aop.jdk;
    2. import java.lang.reflect.Method;
    3. import java.lang.reflect.Proxy;
    4. import java.lang.reflect.UndeclaredThrowableException;
    5. // 代理类会去实现我们的接口
    6. public final class Proxy4 extends Proxy implements UserService {
    7. // 解析所有的方法
    8. private static Method m1;
    9. private static Method m2;
    10. private static Method m3;
    11. private static Method m0;
    12. public Proxy4() throws {
    13. super(paramInvocationHandler);
    14. }
    15. public final boolean equals() throws {
    16. try {
    17. return ((Boolean) this.h.invoke(this, m1, new Object[]{paramObject})).booleanValue();
    18. } catch (RuntimeException localRuntimeException) {
    19. throw localRuntimeException;
    20. } catch (Throwable localThrowable) {
    21. throw new UndeclaredThrowableException(localThrowable);
    22. }
    23. }
    24. public final String toString() throws {
    25. try {
    26. return ((String) this.h.invoke(this, m2, null));
    27. } catch (RuntimeException localRuntimeException) {
    28. throw localRuntimeException;
    29. } catch (Throwable localThrowable) {
    30. throw new UndeclaredThrowableException(localThrowable);
    31. }
    32. }
    33. public final void add() throws {
    34. try {
    35. // 通过InvocationHandler的invoke方法去执行增强和原有方法逻辑
    36. this.h.invoke(this, m3, null);
    37. return;
    38. } catch (RuntimeException localRuntimeException) {
    39. throw localRuntimeException;
    40. } catch (Throwable localThrowable) {
    41. throw new UndeclaredThrowableException(localThrowable);
    42. }
    43. }
    44. public final int hashCode() throws {
    45. try {
    46. return ((Integer) this.h.invoke(this, m0, null)).intValue();
    47. } catch (RuntimeException localRuntimeException) {
    48. throw localRuntimeException;
    49. } catch (Throwable localThrowable) {
    50. throw new UndeclaredThrowableException(localThrowable);
    51. }
    52. }
    53. static {
    54. try {
    55. // 解析所有的method出来
    56. m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
    57. m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
    58. m3 = Class.forName("com.fcant.aop.jdk.UserService").getMethod("add", new Class[0]);
    59. m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
    60. return;
    61. } catch (NoSuchMethodException localNoSuchMethodException) {
    62. throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    63. } catch (ClassNotFoundException localClassNotFoundException) {
    64. throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    65. }
    66. }
    67. }

    从结果可以看出,代理类会实现我们的接口,并会实现我们接口中的方法。然后通过InvocationHandler的invoke方法去执行增强逻辑和原有方法逻辑。在invoke中可以使用反射去执行原有逻辑,并在方法执行前后加上自己的增强逻辑。

    JdkDynamicAopProxy

    JdkDynamicAopProxy是Spring中JDK动态代理的实现,它也实现了InvocationHandler接口。核心方法:

  8. getProxy:获取代理对象,这个和上面的示例几乎是一样的

  9. invoke:实现了AOP的核心逻辑

源码:

  1. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
  2. ...
  3. /** Config used to configure this proxy(对增强器的支持) */
  4. private final AdvisedSupport advised;
  5. ...
  6. public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
  7. Assert.notNull(config, "AdvisedSupport must not be null");
  8. if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
  9. throw new AopConfigException("No advisors and no TargetSource specified");
  10. }
  11. this.advised = config;
  12. }
  13. @Override
  14. public Object getProxy() {
  15. return getProxy(ClassUtils.getDefaultClassLoader());
  16. }
  17. @Override
  18. public Object getProxy(ClassLoader classLoader) {
  19. if (logger.isDebugEnabled()) {
  20. logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
  21. }
  22. // 获取目标类接口
  23. Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
  24. findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
  25. // 返回代理对象
  26. return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
  27. }
  28. ...
  29. /**
  30. * Implementation of {@code InvocationHandler.invoke}.
  31. * <p>Callers will see exactly the exception thrown by the target,
  32. * unless a hook method throws an exception.
  33. */
  34. @Override
  35. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  36. MethodInvocation invocation;
  37. Object oldProxy = null;
  38. boolean setProxyContext = false;
  39. TargetSource targetSource = this.advised.targetSource;
  40. Class<?> targetClass = null;
  41. Object target = null;
  42. try {
  43. // equals 方法处理
  44. if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
  45. // The target does not implement the equals(Object) method itself.
  46. return equals(args[0]);
  47. }
  48. // hashCode 方法处理
  49. else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
  50. // The target does not implement the hashCode() method itself.
  51. return hashCode();
  52. }
  53. else if (method.getDeclaringClass() == DecoratingProxy.class) {
  54. // There is only getDecoratedClass() declared -> dispatch to proxy config.
  55. return AopProxyUtils.ultimateTargetClass(this.advised);
  56. }
  57. else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
  58. method.getDeclaringClass().isAssignableFrom(Advised.class)) {
  59. // Service invocations on ProxyConfig with the proxy config...
  60. return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
  61. }
  62. Object retVal;
  63. // 有时候目标对象内部的自我调用无法实施切面中的增强则需要通过此属性暴露代理
  64. if (this.advised.exposeProxy) {
  65. // Make invocation available if necessary.
  66. oldProxy = AopContext.setCurrentProxy(proxy);
  67. setProxyContext = true;
  68. }
  69. // May be null. Get as late as possible to minimize the time we "own" the target,
  70. // in case it comes from a pool.
  71. target = targetSource.getTarget();
  72. if (target != null) {
  73. targetClass = target.getClass();
  74. }
  75. // 获取当前方法的拦截链
  76. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
  77. if (chain.isEmpty()) {
  78. // 如果没有拦截链那么直接调用切点方法
  79. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
  80. retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
  81. }
  82. else {
  83. // 将拦截器封装在ReflectiveMethodInvocation中,以便使用proceed方法执行拦截链
  84. invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
  85. // 执行拦截链
  86. retVal = invocation.proceed();
  87. }
  88. // Massage return value if necessary.
  89. Class<?> returnType = method.getReturnType();
  90. if (retVal != null && retVal == target &&
  91. returnType != Object.class && returnType.isInstance(proxy) &&
  92. !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
  93. // Special case: it returned "this" and the return type of the method
  94. // is type-compatible. Note that we can't help if the target sets
  95. // a reference to itself in another returned object.
  96. retVal = proxy;
  97. }
  98. else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
  99. throw new AopInvocationException(
  100. "Null return value from advice does not match primitive return type for: " + method);
  101. }
  102. return retVal;
  103. }
  104. finally {
  105. if (target != null && !targetSource.isStatic()) {
  106. // Must have come from TargetSource.
  107. targetSource.releaseTarget(target);
  108. }
  109. if (setProxyContext) {
  110. // Restore old proxy.
  111. AopContext.setCurrentProxy(oldProxy);
  112. }
  113. }
  114. }
  115. ...
  116. }

GCLIB代理

cglib(Code Generation Library)是一个强大的,高性能,高质量的Code生成类库。它可以在运行期扩展Java类与实现Java接口。

  • cglib封装了asm,可以在运行期动态生成新的class(子类)。
  • cglib用于AOP,jdk中的proxy必须基于接口,cglib却没有这个限制。

    示例

    需要代理的类
    1. public class EnhancerDemo {
    2. public void test() {
    3. System.out.println("-------------业务逻辑方法 test ------------");
    4. }
    5. }
    MethodInterceptor的实现类(增强器)
    1. import org.springframework.cglib.proxy.MethodInterceptor;
    2. import org.springframework.cglib.proxy.MethodProxy;
    3. import java.lang.reflect.Method;
    4. public class MethodInterceptorImpl implements MethodInterceptor {
    5. @Override
    6. public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    7. System.out.println("-------------方法执行前的增强逻辑 ------------" + method);
    8. Object result = methodProxy.invokeSuper(object, args);
    9. System.out.println("-------------方法执行后的增强逻辑 ------------" + method);
    10. return result;
    11. }
    12. }
    测试类:
    1. public class EnhancerTest {
    2. @Test
    3. public void contextTest() {
    4. System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\class");
    5. Enhancer enhancer = new Enhancer();
    6. enhancer.setSuperclass(EnhancerDemo.class);
    7. enhancer.setCallback(new MethodInterceptorImpl());
    8. EnhancerDemo proxy = (EnhancerDemo) enhancer.create();
    9. proxy.test();
    10. System.out.println(proxy);
    11. }
    12. }
    执行结果
    1. Connected to the target VM, address: '127.0.0.1:61217', transport: 'socket'
    2. -------------方法执行前的增强逻辑 ------------public void com.fcant.aop.cglib.EnhancerDemo.test()
    3. -------------业务逻辑方法 test ------------
    4. -------------方法执行后的增强逻辑 ------------public void com.fcant.aop.cglib.EnhancerDemo.test()
    5. -------------方法执行前的增强逻辑 ------------public java.lang.String java.lang.Object.toString()
    6. -------------方法执行前的增强逻辑 ------------public native int java.lang.Object.hashCode()
    7. -------------方法执行后的增强逻辑 ------------public native int java.lang.Object.hashCode()
    8. -------------方法执行后的增强逻辑 ------------public java.lang.String java.lang.Object.toString()
    9. com.fcant.aop.cglib.EnhancerDemo$$EnhancerByCGLIB$$da6c48f9@7a187f14
    10. Disconnected from the target VM, address: '127.0.0.1:61217', transport: 'socket'
    可以看到 System.out.println(porxy); 首先调用了 toString() 方法,然后又调用了 hashCode() ,生成的对象为 EnhancerDemo$$EnhancerByCGLIB$$da6c48f9@7a187f14 的实例,这个类是运行时由 CGLIB 产生。

    反编译代理结果

    在测试类的第一行加上下面语句,那么在cglib中生成的class文件将会持久化到硬盘。
    1. // 该设置用于输出cglib动态代理产生的类
    2. System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\class");
    3. // 该设置用于输出jdk动态代理产生的类
    4. System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
    反编译结果:
    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by Fernflower decompiler)
    4. //
    5. package com.fcant.aop.cglib;
    6. import java.lang.reflect.Method;
    7. import org.springframework.cglib.core.ReflectUtils;
    8. import org.springframework.cglib.core.Signature;
    9. import org.springframework.cglib.proxy.Callback;
    10. import org.springframework.cglib.proxy.Factory;
    11. import org.springframework.cglib.proxy.MethodInterceptor;
    12. import org.springframework.cglib.proxy.MethodProxy;
    13. public class EnhancerDemo$$EnhancerByCGLIB$$da6c48f9 extends EnhancerDemo implements Factory {
    14. private boolean CGLIB$BOUND;
    15. public static Object CGLIB$FACTORY_DATA;
    16. private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    17. private static final Callback[] CGLIB$STATIC_CALLBACKS;
    18. private MethodInterceptor CGLIB$CALLBACK_0;
    19. private static Object CGLIB$CALLBACK_FILTER;
    20. private static final Method CGLIB$test$0$Method;
    21. private static final MethodProxy CGLIB$test$0$Proxy;
    22. private static final Object[] CGLIB$emptyArgs;
    23. private static final Method CGLIB$equals$1$Method;
    24. private static final MethodProxy CGLIB$equals$1$Proxy;
    25. private static final Method CGLIB$toString$2$Method;
    26. private static final MethodProxy CGLIB$toString$2$Proxy;
    27. private static final Method CGLIB$hashCode$3$Method;
    28. private static final MethodProxy CGLIB$hashCode$3$Proxy;
    29. private static final Method CGLIB$clone$4$Method;
    30. private static final MethodProxy CGLIB$clone$4$Proxy;
    31. static void CGLIB$STATICHOOK1() {
    32. CGLIB$THREAD_CALLBACKS = new ThreadLocal();
    33. CGLIB$emptyArgs = new Object[0];
    34. Class var0 = Class.forName("com.fcant.aop.cglib.EnhancerDemo$$EnhancerByCGLIB$$da6c48f9");
    35. Class var1;
    36. Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
    37. CGLIB$equals$1$Method = var10000[0];
    38. CGLIB$equals$1$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
    39. CGLIB$toString$2$Method = var10000[1];
    40. CGLIB$toString$2$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
    41. CGLIB$hashCode$3$Method = var10000[2];
    42. CGLIB$hashCode$3$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$3");
    43. CGLIB$clone$4$Method = var10000[3];
    44. CGLIB$clone$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
    45. CGLIB$test$0$Method = ReflectUtils.findMethods(new String[]{"test", "()Ljava/lang/String;"}, (var1 = Class.forName("com.fcant.aop.cglib.EnhancerDemo")).getDeclaredMethods())[0];
    46. CGLIB$test$0$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "test", "CGLIB$test$0");
    47. }
    48. final String CGLIB$test$0() {
    49. return super.test();
    50. }
    51. public final String test() {
    52. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    53. if (var10000 == null) {
    54. CGLIB$BIND_CALLBACKS(this);
    55. var10000 = this.CGLIB$CALLBACK_0;
    56. }
    57. return var10000 != null ? (String)var10000.intercept(this, CGLIB$test$0$Method, CGLIB$emptyArgs, CGLIB$test$0$Proxy) : super.test();
    58. }
    59. final boolean CGLIB$equals$1(Object var1) {
    60. return super.equals(var1);
    61. }
    62. public final boolean equals(Object var1) {
    63. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    64. if (var10000 == null) {
    65. CGLIB$BIND_CALLBACKS(this);
    66. var10000 = this.CGLIB$CALLBACK_0;
    67. }
    68. if (var10000 != null) {
    69. Object var2 = var10000.intercept(this, CGLIB$equals$1$Method, new Object[]{var1}, CGLIB$equals$1$Proxy);
    70. return var2 == null ? false : (Boolean)var2;
    71. } else {
    72. return super.equals(var1);
    73. }
    74. }
    75. final String CGLIB$toString$2() {
    76. return super.toString();
    77. }
    78. public final String toString() {
    79. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    80. if (var10000 == null) {
    81. CGLIB$BIND_CALLBACKS(this);
    82. var10000 = this.CGLIB$CALLBACK_0;
    83. }
    84. return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$2$Method, CGLIB$emptyArgs, CGLIB$toString$2$Proxy) : super.toString();
    85. }
    86. final int CGLIB$hashCode$3() {
    87. return super.hashCode();
    88. }
    89. public final int hashCode() {
    90. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    91. if (var10000 == null) {
    92. CGLIB$BIND_CALLBACKS(this);
    93. var10000 = this.CGLIB$CALLBACK_0;
    94. }
    95. if (var10000 != null) {
    96. Object var1 = var10000.intercept(this, CGLIB$hashCode$3$Method, CGLIB$emptyArgs, CGLIB$hashCode$3$Proxy);
    97. return var1 == null ? 0 : ((Number)var1).intValue();
    98. } else {
    99. return super.hashCode();
    100. }
    101. }
    102. final Object CGLIB$clone$4() throws CloneNotSupportedException {
    103. return super.clone();
    104. }
    105. protected final Object clone() throws CloneNotSupportedException {
    106. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    107. if (var10000 == null) {
    108. CGLIB$BIND_CALLBACKS(this);
    109. var10000 = this.CGLIB$CALLBACK_0;
    110. }
    111. return var10000 != null ? var10000.intercept(this, CGLIB$clone$4$Method, CGLIB$emptyArgs, CGLIB$clone$4$Proxy) : super.clone();
    112. }
    113. public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
    114. String var10000 = var0.toString();
    115. switch(var10000.hashCode()) {
    116. case -508378822:
    117. if (var10000.equals("clone()Ljava/lang/Object;")) {
    118. return CGLIB$clone$4$Proxy;
    119. }
    120. break;
    121. case 225925469:
    122. if (var10000.equals("test()Ljava/lang/String;")) {
    123. return CGLIB$test$0$Proxy;
    124. }
    125. break;
    126. case 1826985398:
    127. if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
    128. return CGLIB$equals$1$Proxy;
    129. }
    130. break;
    131. case 1913648695:
    132. if (var10000.equals("toString()Ljava/lang/String;")) {
    133. return CGLIB$toString$2$Proxy;
    134. }
    135. break;
    136. case 1984935277:
    137. if (var10000.equals("hashCode()I")) {
    138. return CGLIB$hashCode$3$Proxy;
    139. }
    140. }
    141. return null;
    142. }
    143. public EnhancerDemo$$EnhancerByCGLIB$$da6c48f9() {
    144. CGLIB$BIND_CALLBACKS(this);
    145. }
    146. public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
    147. CGLIB$THREAD_CALLBACKS.set(var0);
    148. }
    149. public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
    150. CGLIB$STATIC_CALLBACKS = var0;
    151. }
    152. private static final void CGLIB$BIND_CALLBACKS(Object var0) {
    153. EnhancerDemo$$EnhancerByCGLIB$$da6c48f9 var1 = (EnhancerDemo$$EnhancerByCGLIB$$da6c48f9)var0;
    154. if (!var1.CGLIB$BOUND) {
    155. var1.CGLIB$BOUND = true;
    156. Object var10000 = CGLIB$THREAD_CALLBACKS.get();
    157. if (var10000 == null) {
    158. var10000 = CGLIB$STATIC_CALLBACKS;
    159. if (var10000 == null) {
    160. return;
    161. }
    162. }
    163. var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
    164. }
    165. }
    166. public Object newInstance(Callback[] var1) {
    167. CGLIB$SET_THREAD_CALLBACKS(var1);
    168. EnhancerDemo$$EnhancerByCGLIB$$da6c48f9 var10000 = new EnhancerDemo$$EnhancerByCGLIB$$da6c48f9();
    169. CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
    170. return var10000;
    171. }
    172. public Object newInstance(Callback var1) {
    173. CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
    174. EnhancerDemo$$EnhancerByCGLIB$$da6c48f9 var10000 = new EnhancerDemo$$EnhancerByCGLIB$$da6c48f9();
    175. CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
    176. return var10000;
    177. }
    178. public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
    179. CGLIB$SET_THREAD_CALLBACKS(var3);
    180. EnhancerDemo$$EnhancerByCGLIB$$da6c48f9 var10000 = new EnhancerDemo$$EnhancerByCGLIB$$da6c48f9;
    181. switch(var1.length) {
    182. case 0:
    183. var10000.<init>();
    184. CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
    185. return var10000;
    186. default:
    187. throw new IllegalArgumentException("Constructor not found");
    188. }
    189. }
    190. public Callback getCallback(int var1) {
    191. CGLIB$BIND_CALLBACKS(this);
    192. MethodInterceptor var10000;
    193. switch(var1) {
    194. case 0:
    195. var10000 = this.CGLIB$CALLBACK_0;
    196. break;
    197. default:
    198. var10000 = null;
    199. }
    200. return var10000;
    201. }
    202. public void setCallback(int var1, Callback var2) {
    203. switch(var1) {
    204. case 0:
    205. this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
    206. default:
    207. }
    208. }
    209. public Callback[] getCallbacks() {
    210. CGLIB$BIND_CALLBACKS(this);
    211. return new Callback[]{this.CGLIB$CALLBACK_0};
    212. }
    213. public void setCallbacks(Callback[] var1) {
    214. this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
    215. }
    216. static {
    217. CGLIB$STATICHOOK1();
    218. }
    219. }
    从结果上可以看出Cglib是使用继承的方式实现的动态代理。关键代码:
    1. public final String test() {
    2. MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
    3. if (var10000 == null) {
    4. CGLIB$BIND_CALLBACKS(this);
    5. var10000 = this.CGLIB$CALLBACK_0;
    6. }
    7. return var10000 != null ? (String)var10000.intercept(this, CGLIB$test$0$Method, CGLIB$emptyArgs, CGLIB$test$0$Proxy) : super.test();
    8. }
    从上面的代码可以发现方法的执行会委托给MethodInterceptor的intercept方法。从而实现对方法的增强。 :::tips 由于 Cglib 是使用继承方式,所有final类是不能使用cglib代理的,会直接抛出异常,final方法也将不会被代理,因为不能覆盖,不会直接抛出异常 :::

    CglibAopProxy

    CglibAopProxy是Spring中Cglib动态代理的实现,在getProxy方法中完成了对Enhancer的创建和封装。在getProxy方法中getCallbacks(rootClass);方法会将拦截链封装成DynamicAdvisedInterceptor对象,并放到Cglib的回调函数中。源码如下:
    1. @Override
    2. public Object getProxy(ClassLoader classLoader) {
    3. if (logger.isDebugEnabled()) {
    4. logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    5. }
    6. try {
    7. Class<?> rootClass = this.advised.getTargetClass();
    8. Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
    9. Class<?> proxySuperClass = rootClass;
    10. if (ClassUtils.isCglibProxyClass(rootClass)) {
    11. proxySuperClass = rootClass.getSuperclass();
    12. Class<?>[] additionalInterfaces = rootClass.getInterfaces();
    13. for (Class<?> additionalInterface : additionalInterfaces) {
    14. this.advised.addInterface(additionalInterface);
    15. }
    16. }
    17. // 验证Class
    18. validateClassIfNecessary(proxySuperClass, classLoader);
    19. // 创建以及配置Enhancer
    20. Enhancer enhancer = createEnhancer();
    21. if (classLoader != null) {
    22. enhancer.setClassLoader(classLoader);
    23. if (classLoader instanceof SmartClassLoader &&
    24. ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
    25. enhancer.setUseCache(false);
    26. }
    27. }
    28. enhancer.setSuperclass(proxySuperClass);
    29. enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
    30. enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    31. enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
    32. // 将拦截链放到回调中
    33. Callback[] callbacks = getCallbacks(rootClass);
    34. Class<?>[] types = new Class<?>[callbacks.length];
    35. for (int x = 0; x < types.length; x++) {
    36. types[x] = callbacks[x].getClass();
    37. }
    38. // fixedInterceptorMap only populated at this point, after getCallbacks call above
    39. enhancer.setCallbackFilter(new ProxyCallbackFilter(
    40. this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
    41. enhancer.setCallbackTypes(types);
    42. // 生成代理类并创建代理实例
    43. return createProxyClassAndInstance(enhancer, callbacks);
    44. }
    45. ...
    46. }
    47. private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
    48. // Parameters used for optimization choices...
    49. boolean exposeProxy = this.advised.isExposeProxy();
    50. boolean isFrozen = this.advised.isFrozen();
    51. boolean isStatic = this.advised.getTargetSource().isStatic();
    52. // Choose an "aop" interceptor (used for AOP calls).
    53. // 将拦截链封装到DynamicAdvisedInterceptor中
    54. Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
    55. // Choose a "straight to target" interceptor. (used for calls that are
    56. // unadvised but can return this). May be required to expose the proxy.
    57. Callback targetInterceptor;
    58. if (exposeProxy) {
    59. targetInterceptor = isStatic ?
    60. new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
    61. new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
    62. }
    63. else {
    64. targetInterceptor = isStatic ?
    65. new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
    66. new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
    67. }
    68. // Choose a "direct to target" dispatcher (used for
    69. // unadvised calls to static targets that cannot return this).
    70. Callback targetDispatcher = isStatic ?
    71. new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
    72. Callback[] mainCallbacks = new Callback[] {
    73. // 将拦截链加入到CallBack中
    74. aopInterceptor, // for normal advice
    75. targetInterceptor, // invoke target without considering advice, if optimized
    76. new SerializableNoOp(), // no override for methods mapped to this
    77. targetDispatcher, this.advisedDispatcher,
    78. new EqualsInterceptor(this.advised),
    79. new HashCodeInterceptor(this.advised)
    80. };
    81. Callback[] callbacks;
    82. // If the target is a static one and the advice chain is frozen,
    83. // then we can make some optimizations by sending the AOP calls
    84. // direct to the target using the fixed chain for that method.
    85. if (isStatic && isFrozen) {
    86. Method[] methods = rootClass.getMethods();
    87. Callback[] fixedCallbacks = new Callback[methods.length];
    88. this.fixedInterceptorMap = new HashMap<String, Integer>(methods.length);
    89. // TODO: small memory optimization here (can skip creation for methods with no advice)
    90. for (int x = 0; x < methods.length; x++) {
    91. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
    92. fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
    93. chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
    94. this.fixedInterceptorMap.put(methods[x].toString(), x);
    95. }
    96. // Now copy both the callbacks from mainCallbacks
    97. // and fixedCallbacks into the callbacks array.
    98. callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
    99. System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
    100. System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
    101. this.fixedInterceptorOffset = mainCallbacks.length;
    102. }
    103. else {
    104. callbacks = mainCallbacks;
    105. }
    106. return callbacks;
    107. }

    原理区别

    java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。而cglib动态代理是利用asm开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。
  1. 如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP
  2. 如果目标对象实现了接口,可以强制使用CGLIB实现AOP
  3. 如果目标对象没有实现了接口,必须采用CGLIB库,Spring会自动在JDK动态代理和CGLIB之间转换

    Cglib 与 JDK动态代理的运行性能比较

    结论:从 jdk6 到 jdk7、jdk8 ,动态代理的性能得到了显著的提升,尤其是JDK7和JDK8性能表现都比cglib好,而 cglib 的表现并未跟上,甚至可能会略微下降。所以建议尽量使用 JDK 的动态代理。