一、什么是CGLIB?
CGLIB是一個功能強大,高性能的代碼生成包。它為沒有實現接口的類提供代理,為JDK的動態代理提供了很好的補充。通常可以使用Java的動態代理創建代理,但當要代理的類沒有實現接口或者為了更好的性能,CGLIB是一個好的選擇。
二、CGLIB原理
CGLIB原理:動態生成一個要代理類的子類,子類重寫要代理的類的所有不是final的方法。在子類中采用方法攔截的技術攔截所有父類方法的調用,順勢織入橫切邏輯。它比使用java反射的JDK動態代理要快。
CGLIB底層:使用字節碼處理框架ASM,來轉換字節碼並生成新的類。不鼓勵直接使用ASM,因為它要求你必須對JVM內部結構包括class文件的格式和指令集都很熟悉。
CGLIB缺點:對於final方法,無法進行代理。
三、CGLIB的應用
廣泛的被許多AOP的框架使用,例如Spring AOP和dynaop。Hibernate使用CGLIB來代理單端single-ended(多對一和一對一)關聯。
四、CGLIB的API
1、Jar包:
cglib-nodep-2.2.jar:使用nodep包不需要關聯asm的jar包,jar包內部包含asm的類.
cglib-2.2.jar:使用此jar包需要關聯asm的jar包,否則運行時報錯.
2、CGLIB類庫:
由於基本代碼很少,學起來有一定的困難,主要是缺少文檔和示例,這也是CGLIB的一個不足之處。
本系列使用的CGLIB版本是2.2。
net.sf.cglib.core:底層字節碼處理類,他們大部分與ASM有關系。
net.sf.cglib.transform:編譯期或運行期類和類文件的轉換
net.sf.cglib.proxy:實現創建代理和方法攔截器的類
net.sf.cglib.reflect:實現快速反射和C#風格代理的類
net.sf.cglib.util:集合排序等工具類
net.sf.cglib.beans:JavaBean相關的工具類
本篇介紹通過MethodInterceptor和Enhancer實現一個動態代理。
一、首先說一下JDK中的動態代理:
JDK中的動態代理是通過反射類Proxy以及InvocationHandler回調接口實現的,
但是,JDK中所要進行動態代理的類必須要實現一個接口,也就是說只能對該類所實現接口中定義的方法進行代理,這在實際編程中具有一定的局限性,而且使用反射的效率也並不是很高。
二、使用CGLib實現:
使用CGLib實現動態代理,完全不受代理類必須實現接口的限制,而且CGLib底層采用ASM字節碼生成框架,使用字節碼技術生成代理類,比使用Java反射效率要高。唯一需要注意的是,CGLib不能對聲明為final的方法進行代理,因為CGLib原理是動態生成被代理類的子類。
下面,將通過一個實例介紹使用CGLib實現動態代理。
1、被代理類:
首先,定義一個類,該類沒有實現任何接口
1 package com.zghw.cglib; 2 3 /** 4 * 沒有實現接口,需要CGlib動態代理的目標類 5 * 6 * @author zghw 7 * 8 */ 9 public class TargetObject { 10 public String method1(String paramName) { 11 return paramName; 12 } 13 14 public int method2(int count) { 15 return count; 16 } 17 18 public int method3(int count) { 19 return count; 20 } 21 22 @Override 23 public String toString() { 24 return "TargetObject []"+ getClass(); 25 } 26 }</span>
2、攔截器:
定義一個攔截器。在調用目標方法時,CGLib會回調MethodInterceptor接口方法攔截,來實現你自己的代理邏輯,類似於JDK中的InvocationHandler接口。
1 package com.zghw.cglib; 2 3 import java.lang.reflect.Method; 4 import net.sf.cglib.proxy.MethodInterceptor; 5 import net.sf.cglib.proxy.MethodProxy; 6 /** 7 * 目標對象攔截器,實現MethodInterceptor 8 * @author zghw 9 * 10 */ 11 public class TargetInterceptor implements MethodInterceptor{ 12 /** 13 * 重寫方法攔截在方法前和方法后加入業務 14 * Object obj為目標對象 15 * Method method為目標方法 16 * Object[] params 為參數, 17 * MethodProxy proxy CGlib方法代理對象 18 */ 19 @Override 20 public Object intercept(Object obj, Method method, Object[] params, 21 MethodProxy proxy) throws Throwable { 22 System.out.println("調用前"); 23 Object result = proxy.invokeSuper(obj, params); 24 System.out.println(" 調用后"+result); 25 return result; 26 } 27 }
參數:Object為由CGLib動態生成的代理類實例,Method為上文中實體類所調用的被代理的方法引用,Object[]為參數值列表,MethodProxy為生成的代理類對方法的代理引用。
返回:從代理實例的方法調用返回的值。
其中,proxy.invokeSuper(obj,arg):
調用代理類實例上的proxy方法的父類方法(即實體類TargetObject中對應的方法)
在這個示例中,只在調用被代理類方法前后各打印了一句話,當然實際編程中可以是其它復雜邏輯。
3、生成動態代理類:
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.Callback; 4 import net.sf.cglib.proxy.CallbackFilter; 5 import net.sf.cglib.proxy.Enhancer; 6 import net.sf.cglib.proxy.NoOp; 7 8 public class TestCglib { 9 public static void main(String args[]) { 10 Enhancer enhancer =new Enhancer(); 11 enhancer.setSuperclass(TargetObject.class); 12 enhancer.setCallback(new TargetInterceptor()); 13 TargetObject targetObject2=(TargetObject)enhancer.create(); 14 System.out.println(targetObject2); 15 System.out.println(targetObject2.method1("mmm1")); 16 System.out.println(targetObject2.method2(100)); 17 System.out.println(targetObject2.method3(200)); 18 } 19 }
這里Enhancer類是CGLib中的一個字節碼增強器,它可以方便的對你想要處理的類進行擴展,以后會經常看到它。
首先將被代理類TargetObject設置成父類,然后設置攔截器TargetInterceptor,最后執行enhancer.create()動態生成一個代理類,並從Object強制轉型成父類型TargetObject。
最后,在代理類上調用方法.
4、回調過濾器CallbackFilter
一、作用
在CGLib回調時可以設置對不同方法執行不同的回調邏輯,或者根本不執行回調。
在JDK動態代理中並沒有類似的功能,對InvocationHandler接口方法的調用對代理類內的所以方法都有效。
定義實現過濾器CallbackFilter接口的類:
1 package com.zghw.cglib; 2 3 import java.lang.reflect.Method; 4 import net.sf.cglib.proxy.CallbackFilter; 5 /** 6 * 回調方法過濾 7 * @author zghw 8 * 9 */ 10 public class TargetMethodCallbackFilter implements CallbackFilter { 11 /** 12 * 過濾方法 13 * 返回的值為數字,代表了Callback數組中的索引位置,要到用的Callback 14 */ 15 @Override 16 public int accept(Method method) { 17 if(method.getName().equals("method1")){ 18 System.out.println("filter method1 ==0"); 19 return 0; 20 } 21 if(method.getName().equals("method2")){ 22 System.out.println("filter method2 ==1"); 23 return 1; 24 } 25 if(method.getName().equals("method3")){ 26 System.out.println("filter method3 ==2"); 27 return 2; 28 } 29 return 0; 30 } 31 }
其中return值為被代理類的各個方法在回調數組Callback[]中的位置索引(見下文)。
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.Callback; 4 import net.sf.cglib.proxy.CallbackFilter; 5 import net.sf.cglib.proxy.Enhancer; 6 import net.sf.cglib.proxy.NoOp; 7 8 public class TestCglib { 9 public static void main(String args[]) { 10 Enhancer enhancer =new Enhancer(); 11 enhancer.setSuperclass(TargetObject.class); 12 CallbackFilter callbackFilter = new TargetMethodCallbackFilter(); 13 14 /** 15 * (1)callback1:方法攔截器 16 (2)NoOp.INSTANCE:這個NoOp表示no operator,即什么操作也不做,代理類直接調用被代理的方法不進行攔截。 17 (3)FixedValue:表示鎖定方法返回值,無論被代理類的方法返回什么值,回調方法都返回固定值。 18 */ 19 Callback noopCb=NoOp.INSTANCE; 20 Callback callback1=new TargetInterceptor(); 21 Callback fixedValue=new TargetResultFixed(); 22 Callback[] cbarray=new Callback[]{callback1,noopCb,fixedValue}; 23 //enhancer.setCallback(new TargetInterceptor()); 24 enhancer.setCallbacks(cbarray); 25 enhancer.setCallbackFilter(callbackFilter); 26 TargetObject targetObject2=(TargetObject)enhancer.create(); 27 System.out.println(targetObject2); 28 System.out.println(targetObject2.method1("mmm1")); 29 System.out.println(targetObject2.method2(100)); 30 System.out.println(targetObject2.method3(100)); 31 System.out.println(targetObject2.method3(200)); 32 } 33 }
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.FixedValue; 4 /** 5 * 表示鎖定方法返回值,無論被代理類的方法返回什么值,回調方法都返回固定值。 6 * @author zghw 7 * 8 */ 9 public class TargetResultFixed implements FixedValue{ 10 11 /** 12 * 該類實現FixedValue接口,同時鎖定回調值為999 13 * (整型,CallbackFilter中定義的使用FixedValue型回調的方法為getConcreteMethodFixedValue,該方法返回值為整型)。 14 */ 15 @Override 16 public Object loadObject() throws Exception { 17 System.out.println("鎖定結果"); 18 Object obj = 999; 19 return obj; 20 } 21 22 }
5.延遲加載對象
一、作用:
說到延遲加載,應該經常接觸到,尤其是使用Hibernate的時候,本篇將通過一個實例分析延遲加載的實現方式。
LazyLoader接口繼承了Callback,因此也算是CGLib中的一種Callback類型。
另一種延遲加載接口Dispatcher。
Dispatcher接口同樣繼承於Callback,也是一種回調類型。
但是Dispatcher和LazyLoader的區別在於:LazyLoader只在第一次訪問延遲加載屬性時觸發代理類回調方法,而Dispatcher在每次訪問延遲加載屬性時都會觸發代理類回調方法。
二、示例:
首先定義一個實體類LoaderBean,該Bean內有一個需要延遲加載的屬性PropertyBean。
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.Enhancer; 4 5 public class LazyBean { 6 private String name; 7 private int age; 8 private PropertyBean propertyBean; 9 private PropertyBean propertyBeanDispatcher; 10 11 public LazyBean(String name, int age) { 12 System.out.println("lazy bean init"); 13 this.name = name; 14 this.age = age; 15 this.propertyBean = createPropertyBean(); 16 this.propertyBeanDispatcher = createPropertyBeanDispatcher(); 17 } 18 19 20 21 /** 22 * 只第一次懶加載 23 * @return 24 */ 25 private PropertyBean createPropertyBean() { 26 /** 27 * 使用cglib進行懶加載 對需要延遲加載的對象添加代理,在獲取該對象屬性時先通過代理類回調方法進行對象初始化。 28 * 在不需要加載該對象時,只要不去獲取該對象內屬性,該對象就不會被初始化了(在CGLib的實現中只要去訪問該對象內屬性的getter方法, 29 * 就會自動觸發代理類回調)。 30 */ 31 Enhancer enhancer = new Enhancer(); 32 enhancer.setSuperclass(PropertyBean.class); 33 PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class, 34 new ConcreteClassLazyLoader()); 35 return pb; 36 } 37 /** 38 * 每次都懶加載 39 * @return 40 */ 41 private PropertyBean createPropertyBeanDispatcher() { 42 Enhancer enhancer = new Enhancer(); 43 enhancer.setSuperclass(PropertyBean.class); 44 PropertyBean pb = (PropertyBean) enhancer.create(PropertyBean.class, 45 new ConcreteClassDispatcher()); 46 return pb; 47 } 48 public String getName() { 49 return name; 50 } 51 52 public void setName(String name) { 53 this.name = name; 54 } 55 56 public int getAge() { 57 return age; 58 } 59 60 public void setAge(int age) { 61 this.age = age; 62 } 63 64 public PropertyBean getPropertyBean() { 65 return propertyBean; 66 } 67 68 public void setPropertyBean(PropertyBean propertyBean) { 69 this.propertyBean = propertyBean; 70 } 71 72 public PropertyBean getPropertyBeanDispatcher() { 73 return propertyBeanDispatcher; 74 } 75 76 public void setPropertyBeanDispatcher(PropertyBean propertyBeanDispatcher) { 77 this.propertyBeanDispatcher = propertyBeanDispatcher; 78 } 79 80 @Override 81 public String toString() { 82 return "LazyBean [name=" + name + ", age=" + age + ", propertyBean=" 83 + propertyBean + "]"; 84 } 85 }
1 package com.zghw.cglib; 2 3 public class PropertyBean { 4 private String key; 5 private Object value; 6 public String getKey() { 7 return key; 8 } 9 public void setKey(String key) { 10 this.key = key; 11 } 12 public Object getValue() { 13 return value; 14 } 15 public void setValue(Object value) { 16 this.value = value; 17 } 18 @Override 19 public String toString() { 20 return "PropertyBean [key=" + key + ", value=" + value + "]" +getClass(); 21 } 22 23 }
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.LazyLoader; 4 5 public class ConcreteClassLazyLoader implements LazyLoader { 6 /** 7 * 對需要延遲加載的對象添加代理,在獲取該對象屬性時先通過代理類回調方法進行對象初始化。 8 * 在不需要加載該對象時,只要不去獲取該對象內屬性,該對象就不會被初始化了(在CGLib的實現中只要去訪問該對象內屬性的getter方法, 9 * 就會自動觸發代理類回調)。 10 */ 11 @Override 12 public Object loadObject() throws Exception { 13 System.out.println("before lazyLoader..."); 14 PropertyBean propertyBean = new PropertyBean(); 15 propertyBean.setKey("zghw"); 16 propertyBean.setValue(new TargetObject()); 17 System.out.println("after lazyLoader..."); 18 return propertyBean; 19 } 20 21 }
1 package com.zghw.cglib; 2 3 import net.sf.cglib.proxy.Dispatcher; 4 5 public class ConcreteClassDispatcher implements Dispatcher{ 6 7 @Override 8 public Object loadObject() throws Exception { 9 System.out.println("before Dispatcher..."); 10 PropertyBean propertyBean = new PropertyBean(); 11 propertyBean.setKey("xxx"); 12 propertyBean.setValue(new TargetObject()); 13 System.out.println("after Dispatcher..."); 14 return propertyBean; 15 } 16 17 }
6.接口生成器InterfaceMaker
一、作用:
InterfaceMaker會動態生成一個接口,該接口包含指定類定義的所有方法。
二、示例: