1. 程式人生 > >深入理解CGLIB動態代理機制

深入理解CGLIB動態代理機制

本文是基於CGLIB 3.1進行探究的

cglib is a powerful, high performance and quality Code Generation Library, It is used to extend JAVA classes and implements interfaces at runtime.

在Spring AOP中,通常會用它來生成AopProxy物件。不僅如此,在Hibernate中PO(Persistant Object 持久化物件)位元組碼的生成工作也要靠它來完成。

本文將深入探究CGLIB動態代理的實現機制,配合下面這篇文章一起食用口味更佳:

深入理解JDK動態代理機制

一、CGLIB動態代理示例

下面由一個簡單的示例開始我們對CGLIB動態代理的介紹:

為了後續編碼的順利進行,我們需要使用Maven引入CGLIB的包

圖1.1 被代理類

圖1.2 實現MethodInterceptor介面生成方法攔截器

圖1.3 生成代理類物件並列印在代理類物件呼叫方法之後的執行結果

JDK代理要求被代理的類必須實現介面,有很強的侷限性。而CGLIB動態代理則沒有此類強制性要求。簡單的說,CGLIB會讓生成的代理類繼承被代理類,並在代理類中對代理方法進行強化處理(前置處理、後置處理等)。在CGLIB底層,其實是藉助了ASM這個非常強大的Java位元組碼生成框架。

二、生成代理類物件

從圖1.3中我們看到,代理類物件是由Enhancer類建立的。Enhancer是CGLIB的位元組碼增強器,可以很方便的對類進行拓展,如圖1.3中的為類設定Superclass。

建立代理物件的幾個步驟:

  • 生成代理類的二進位制位元組碼檔案;
  • 載入二進位制位元組碼,生成Class物件( 例如使用Class.forName()方法 );
  • 通過反射機制獲得例項構造,並建立代理類物件

我們來看看將代理類Class檔案反編譯之後的Java程式碼

package proxy;

import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class HelloServiceImpl$$EnhancerByCGLIB$$82ef2d06
  extends HelloServiceImpl
  implements Factory
{
  private boolean CGLIB$BOUND;
  private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
  private static final Callback[] CGLIB$STATIC_CALLBACKS;
  private MethodInterceptor CGLIB$CALLBACK_0;
  private static final Method CGLIB$sayHello$0$Method;
  private static final MethodProxy CGLIB$sayHello$0$Proxy;
  private static final Object[] CGLIB$emptyArgs;
  private static final Method CGLIB$finalize$1$Method;
  private static final MethodProxy CGLIB$finalize$1$Proxy;
  private static final Method CGLIB$equals$2$Method;
  private static final MethodProxy CGLIB$equals$2$Proxy;
  private static final Method CGLIB$toString$3$Method;
  private static final MethodProxy CGLIB$toString$3$Proxy;
  private static final Method CGLIB$hashCode$4$Method;
  private static final MethodProxy CGLIB$hashCode$4$Proxy;
  private static final Method CGLIB$clone$5$Method;
  private static final MethodProxy CGLIB$clone$5$Proxy;
  
  static void CGLIB$STATICHOOK1()
  {
    CGLIB$THREAD_CALLBACKS = new ThreadLocal();
    CGLIB$emptyArgs = new Object[0];
    Class localClass1 = Class.forName("proxy.HelloServiceImpl$$EnhancerByCGLIB$$82ef2d06");
    Class localClass2;
    Method[] tmp95_92 = ReflectUtils.findMethods(new String[] { "finalize", "()V", "equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;" }, (localClass2 = Class.forName("java.lang.Object")).getDeclaredMethods());
    CGLIB$finalize$1$Method = tmp95_92[0];
    CGLIB$finalize$1$Proxy = MethodProxy.create(localClass2, localClass1, "()V", "finalize", "CGLIB$finalize$1");
    Method[] tmp115_95 = tmp95_92;
    CGLIB$equals$2$Method = tmp115_95[1];
    CGLIB$equals$2$Proxy = MethodProxy.create(localClass2, localClass1, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$2");
    Method[] tmp135_115 = tmp115_95;
    CGLIB$toString$3$Method = tmp135_115[2];
    CGLIB$toString$3$Proxy = MethodProxy.create(localClass2, localClass1, "()Ljava/lang/String;", "toString", "CGLIB$toString$3");
    Method[] tmp155_135 = tmp135_115;
    CGLIB$hashCode$4$Method = tmp155_135[3];
    CGLIB$hashCode$4$Proxy = MethodProxy.create(localClass2, localClass1, "()I", "hashCode", "CGLIB$hashCode$4");
    Method[] tmp175_155 = tmp155_135;
    CGLIB$clone$5$Method = tmp175_155[4];
    CGLIB$clone$5$Proxy = MethodProxy.create(localClass2, localClass1, "()Ljava/lang/Object;", "clone", "CGLIB$clone$5");
    tmp175_155;
    Method[] tmp223_220 = ReflectUtils.findMethods(new String[] { "sayHello", "()V" }, (localClass2 = Class.forName("proxy.HelloServiceImpl")).getDeclaredMethods());
    CGLIB$sayHello$0$Method = tmp223_220[0];
    CGLIB$sayHello$0$Proxy = MethodProxy.create(localClass2, localClass1, "()V", "sayHello", "CGLIB$sayHello$0");
    tmp223_220;
    return;
  }
  
  final void CGLIB$sayHello$0()
  {
    super.sayHello();
  }
  
  public final void sayHello()
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    if (this.CGLIB$CALLBACK_0 != null) {
      return;
    }
    super.sayHello();
  }
  
  final void CGLIB$finalize$1()
    throws Throwable
  {
    super.finalize();
  }
  
  protected final void finalize()
    throws Throwable
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    if (this.CGLIB$CALLBACK_0 != null) {
      return;
    }
    super.finalize();
  }
  
  final boolean CGLIB$equals$2(Object paramObject)
  {
    return super.equals(paramObject);
  }
  
  public final boolean equals(Object paramObject)
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    MethodInterceptor tmp17_14 = this.CGLIB$CALLBACK_0;
    if (tmp17_14 != null)
    {
      Object tmp41_36 = tmp17_14.intercept(this, CGLIB$equals$2$Method, new Object[] { paramObject }, CGLIB$equals$2$Proxy);
      tmp41_36;
      return tmp41_36 == null ? false : ((Boolean)tmp41_36).booleanValue();
    }
    return super.equals(paramObject);
  }
  
  final String CGLIB$toString$3()
  {
    return super.toString();
  }
  
  public final String toString()
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    MethodInterceptor tmp17_14 = this.CGLIB$CALLBACK_0;
    if (tmp17_14 != null) {
      return (String)tmp17_14.intercept(this, CGLIB$toString$3$Method, CGLIB$emptyArgs, CGLIB$toString$3$Proxy);
    }
    return super.toString();
  }
  
  final int CGLIB$hashCode$4()
  {
    return super.hashCode();
  }
  
  public final int hashCode()
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    MethodInterceptor tmp17_14 = this.CGLIB$CALLBACK_0;
    if (tmp17_14 != null)
    {
      Object tmp36_31 = tmp17_14.intercept(this, CGLIB$hashCode$4$Method, CGLIB$emptyArgs, CGLIB$hashCode$4$Proxy);
      tmp36_31;
      return tmp36_31 == null ? 0 : ((Number)tmp36_31).intValue();
    }
    return super.hashCode();
  }
  
  final Object CGLIB$clone$5()
    throws CloneNotSupportedException
  {
    return super.clone();
  }
  
  protected final Object clone()
    throws CloneNotSupportedException
  {
    MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0;
    if (tmp4_1 == null)
    {
      tmp4_1;
      CGLIB$BIND_CALLBACKS(this);
    }
    MethodInterceptor tmp17_14 = this.CGLIB$CALLBACK_0;
    if (tmp17_14 != null) {
      return tmp17_14.intercept(this, CGLIB$clone$5$Method, CGLIB$emptyArgs, CGLIB$clone$5$Proxy);
    }
    return super.clone();
  }
  
  public static MethodProxy CGLIB$findMethodProxy(Signature paramSignature)
  {
    String tmp4_1 = paramSignature.toString();
    switch (tmp4_1.hashCode())
    {
    case -1574182249: 
      if (tmp4_1.equals("finalize()V")) {
        return CGLIB$finalize$1$Proxy;
      }
      break;
    }
  }
  
  public HelloServiceImpl$$EnhancerByCGLIB$$82ef2d06()
  {
    CGLIB$BIND_CALLBACKS(this);
  }
  
  public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] paramArrayOfCallback)
  {
    CGLIB$THREAD_CALLBACKS.set(paramArrayOfCallback);
  }
  
  public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] paramArrayOfCallback)
  {
    CGLIB$STATIC_CALLBACKS = paramArrayOfCallback;
  }
  
  private static final void CGLIB$BIND_CALLBACKS(Object paramObject)
  {
    82ef2d06 local82ef2d06 = (82ef2d06)paramObject;
    if (!local82ef2d06.CGLIB$BOUND)
    {
      local82ef2d06.CGLIB$BOUND = true;
      Object tmp23_20 = CGLIB$THREAD_CALLBACKS.get();
      if (tmp23_20 == null)
      {
        tmp23_20;
        CGLIB$STATIC_CALLBACKS;
      }
      local82ef2d06.CGLIB$CALLBACK_0 = (// INTERNAL ERROR //

三、對委託類進行代理

我們上面貼出了生成的代理類原始碼。以我們上面的例子為參考,下面我們總結一下CGLIB在進行代理的時候都進行了哪些工作呢

  • 生成的代理類HelloServiceImpl$$EnhancerByCGLIB$$82ef2d06繼承被代理類HelloServiceImpl。在這裡我們需要注意一點:如果委託類被final修飾,那麼它不可被繼承,即不可被代理;同樣,如果委託類中存在final修飾的方法,那麼該方法也不可被代理;
  • 代理類會為委託方法生成兩個方法,一個是重寫的sayHello方法,另一個是CGLIB$sayHello$0方法,我們可以看到它是直接呼叫父類的sayHello方法;
  • 當執行代理物件的sayHello方法時,會首先判斷一下是否存在實現了MethodInterceptor介面的CGLIB$CALLBACK_0;,如果存在,則將呼叫MethodInterceptor中的intercept方法,如圖2.1。

圖2.1 intercept方法

圖2.2 代理類為每個委託方法都會生成兩個方法

intercept方法中,我們除了會呼叫委託方法,還會進行一些增強操作。在Spring AOP中,典型的應用場景就是在某些敏感方法執行前後進行操作日誌記錄。

我們從圖2.1中看到,呼叫委託方法是通過代理方法的MethodProxy物件呼叫invokeSuper方法來執行的,下面我們看看invokeSuper方法中的玄機:

圖2.3 invokeSuper方法

在這裡好像不能直接看出代理方法的呼叫。沒關係,我會慢慢介紹。 我們知道,在JDK動態代理中方法的呼叫是通過反射來完成的。如果有對此不太瞭解的同學,可以看下我之前的部落格----深入理解JDK動態代理機制。但是在CGLIB中,方法的呼叫並不是通過反射來完成的,而是直接對方法進行呼叫:FastClass對Class物件進行特別的處理,比如將會用陣列儲存method的引用,每次呼叫方法的時候都是通過一個index下標來保持對方法的引用。比如下面的getIndex方法就是通過方法簽名來獲得方法在儲存了Class資訊的陣列中的下標。

圖2.4 getIndex方法

圖2.5 FastClassInfo類中持有兩個FastClass物件的引用.png

以我們上面的sayHello方法為例,f1指向委託類物件,f2指向代理類物件,i1和i2分別代表著sayHello方法以及CGLIB$sayHello$0方法在物件資訊陣列中的下標。

到此為止CGLIB動態代理機制就介紹完了,下面給出三種代理方式之間對比。

代理方式 實現 優點 缺點 特點
JDK靜態代理 代理類與委託類實現同一介面,並且在代理類中需要硬編碼介面 實現簡單,容易理解 代理類需要硬編碼介面,在實際應用中可能會導致重複編碼,浪費儲存空間並且效率很低 好像沒啥特點
JDK動態代理 代理類與委託類實現同一介面,主要是通過代理類實現InvocationHandler並重寫invoke方法來進行動態代理的,在invoke方法中將對方法進行增強處理 不需要硬編碼介面,程式碼複用率高 只能夠代理實現了介面的委託類 底層使用反射機制進行方法的呼叫
CGLIB動態代理 代理類將委託類作為自己的父類併為其中的非final委託方法建立兩個方法,一個是與委託方法簽名相同的方法,它在方法中會通過super呼叫委託方法;另一個是代理類獨有的方法。在代理方法中,它會判斷是否存在實現了MethodInterceptor介面的物件,若存在則將呼叫intercept方法對委託方法進行代理 可以在執行時對類或者是介面進行增強操作,且委託類無需實現介面 不能對final類以及final方法進行代理 底層將方法全部存入一個數組中,通過陣列索引直接進行方法呼叫

作者:EakonZhao 連結:https://www.jianshu.com/p/9a61af393e41 來源:簡書 簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。