CGLIB庫介紹
代理提供了一個可擴展的機制來控制被代理物件的訪問,其實說白了就是在物件訪問的時候加了一層封裝,JDK從1.3版本起就提供了一個動態代理,它使用起來非常簡單,但是有個明顯的缺點:需要目標物件實作一個或多個介面,假如你想代理沒有介面的類呢?可以使用CGLIB庫,
CGLIB是一個強大的、高性能的代碼生成庫,它被廣泛使用在基于代理的AOP框架(例如Spring AOP和dynaop)提供方法攔截,Hibernate作為最流行的ORM工具也同樣使用CGLIB庫來代理單端關聯(集合懶加載除外,它使用另外一種機制),EasyMock和jMock作為流行的Java測驗庫,它們提供Mock物件的方式來支持測驗,都使用了CGLIB來對沒有介面的類進行代理,
在實作內部,CGLIB庫使用了ASM這一個輕量但高性能的位元組碼操作框架來轉化位元組碼,產生新類,除了CGLIB,像Groovy和BeanShell這樣的腳本語言同樣使用ASM來生成Java位元組碼,ASM使用了一個類似于SAX分析器的機制來達到高性能,我們不建議直接使用ASM,因為這樣需要對JVM非常了解,包括類檔案格式和指令集,

上圖展示了CGLIB庫相關框架以及語言之間的關系,另外提醒下,類似于Spring AOP和Hibernate這些框架它們經常同時使用CGLIB和JDK動態代理來滿足各自需要,Hibernate使用JDK動態代理為WebShere應用服務實作一個事務管理配接器;Spring AOP則默認使用JDK動態代理來代理介面,除非你強制使用CGLIB,
CGLIB API
CGLIB庫的代碼量不多,但是由于缺乏檔案導致學習起來比較困難,2.1.2版本的CGLIB庫組織如下所示:
- net.sf.cglib.core:底層位元組碼操作類;大部分與ASP相關,
- net.sf.cglib.transform:編譯期、運行期的class檔案轉換類,
- net.sf.cglib.proxy:代理創建類、方法攔截類,
- net.sf.cglib.reflect:更快的反射類、C#風格的代理類,
- net.sf.cglib.util:集合排序工具類
- net.sf.cglib.beans:JavaBean相關的工具類
對于創建動態代理,大部分情況下你只需要使用proxy包的一部分API即可,
上面已經提到,CGLIB庫是基于ASM的上層應用,對于代理沒有實作介面的類,CGLIB非常實用,本質上來說,對于需要被代理的類,它只是動態生成一個子類以覆寫非final的方法,同時系結鉤子回呼自定義的攔截器,值得說的是,它比JDK動態代理還要快,

CGLIB庫中經常用來代理類的API關聯圖如上所示,net.sf.cglib.proxy.Callback只是一個用于標記的介面,net.sf.cglib.proxy.Enhancer使用的所有回呼都會繼承這個介面,
net.sf.cglib.proxy.MethodInterceptor是最常用的回呼型別,在基于代理的AOP實作中它經常被用來攔截方法呼叫,這個介面只有一個方法:
public Object intercept(Object object, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable;
如果net.sf.cglib.proxy.MethodInterceptor被設定為方法回呼,那么當呼叫代理方法時,它會先呼叫MethodInterceptor.intercept方法,然后再呼叫被代理物件的方法(如下圖所示),MethodInterceptor.intercept方法的第一個引數是代理物件,第二個、第三個引數分別是被攔截的方法和方法的引數,如果想呼叫被代理物件的原始方法,可以通過使用java.lang.reflect.Method物件來反射呼叫,或者使用net.sf.cglib.proxy.MethodProxy物件,我們通常使用net.sf.cglib.proxy.MethodProxy因為它更快,在intercept方法中,自定義代碼可以在原始方法呼叫前或呼叫后注入,

net.sf.cglib.proxy.MethodInterceptor滿足了所有的代理需求,但對于某些特定場景它可能使用起來不太方便,為了方便使用和高性能,CGLIB提供了另外一些特殊的回呼型別,例如,
- net.sf.cglib.proxy.FixedValue:在強制一個特定方法回傳固定值,在特定場景下非常有用且性能高,
- net.sf.cglib.proxy.NoOp:它直接透傳到父類的方法實作,
- net.sf.cglib.proxy.LazyLoader:在被代理物件需要懶加載場景下非常有用,如果被代理物件加載完成,那么在以后的代理呼叫時會重復使用,
- net.sf.cglib.proxy.Dispatcher:與net.sf.cglib.proxy.LazyLoader差不多,但每次呼叫代理方法時都會呼叫loadObject方法來加載被代理物件,
- net.sf.cglib.proxy.ProxyRefDispatcher:與Dispatcher相同,但它的loadObject方法支持傳入代理物件,
我們通常對于被代理類的所有方法都使用同樣的回呼(如上圖Figure 3所示),但我們也可以使用net.sf.cglib.proxy.CallbackFilter來對不同的方法使用不同的回呼,這種細粒度的控制是JDK動態代理沒有提供的,JDK中的java.lang.reflect.InvocationHandler的invoke方法只能應用于被代理物件的所有方法,
除了代理類之外,CGLIB也可以通過java.lang.reflect.Proxy插入替換的方式來代理介面以支持JDK1.3之前的代理,但由于這種替換代理很少用,因此這里省略相關的代理API,
現在讓我們看看怎么使用CGLIB來創建代理吧,
簡單代理
CGLIB代理的核心是net.sf.cglib.proxy.Enhancer類,對于創建一個CGLIB代理,你最少得有一個被代理類,現在我們先使用內置的NoOp回呼:
/**
* Create a proxy using NoOp callback. The target class
* must have a default zero-argument constructor.
* @param targetClass the super class of the proxy
* @return a new proxy for a target class instance
*/
public Object createProxy(Class targetClass) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetClass);
enhancer.setCallback(NoOp.INSTANCE);
return enhancer.create();
}
這個方法的回傳值是一個目標類物件的代理,在上面這個例子中,net.sf.cglib.proxy.Enhancer配置了單個net.sf.cglib.proxy.Callback,可以看到,使用CGLIB創建一個簡單代理是很容易的,除了創建一個新的net.sf.cglib.proxy.Enhancer物件,你也可以直接使用net.sf.cglib.proxy.Enhancer類中的靜態輔助方法來創建代理,但我們更推薦使用例子中的方法,因為你可以通過配置net.sf.cglib.proxy.Enhancer物件來對產生的代理進行更精細的控制,
值得注意的是,我們傳入目標類作為代理的父類,不同于JDK動態代理,我們不能使用目標物件來創建代理,目標物件只能被CGLIB創建,在例子中,默認的無參構造方法被使用來創建目標物件,如果你希望CGLIB創建一個有引數的實體,你應該使用net.sf.cglib.proxy.Enhancer.create(Class[], Object[]),該方法的第一個引數指明引數型別,第二個引數指明引數值,引數中的原子型別需要使用包裝類,
使用MethodInterceptor
我們可以將net.sf.cglib.proxy.NoOp回呼替換成自定義的net.sf.cglib.proxy.MethodInterceptor來得到更強大的代理,代理的所有方法呼叫都會被分派給net.sf.cglib.proxy.MethodInterceptor的intercept方法,intercept方法然后呼叫底層物件,
假設你想對目標物件的方法呼叫進行授權檢查,如果授權失敗,那么拋出一個運行時例外AuthorizationException,介面Authorization.java如下:
package com.lizjason.cglibproxy;
import java.lang.reflect.Method;
/**
* A simple authorization service for illustration purpose.
*
* @author Jason Zhicheng Li ([email protected])
*/
10public interface AuthorizationService {
/**
* Authorization check for a method call. An AuthorizationException
* will be thrown if the check fails.
*/
void authorize(Method method);
}
介面net.sf.cglib.proxy.MethodInterceptor的實作如下:
package com.lizjason.cglibproxy.impl;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.lizjason.cglibproxy.AuthorizationService;
/**
* A simple MethodInterceptor implementation to
* apply authorization checks for proxy method calls.
*
* @author Jason Zhicheng Li ([email protected])
*
*/
public class AuthorizationInterceptor implements MethodInterceptor {
private AuthorizationService authorizationService;
/**
* Create a AuthorizationInterceptor with the given
* AuthorizationService
*/
public AuthorizationInterceptor (AuthorizationService authorizationService) {
this.authorizationService = authorizationService;
}
/**
* Intercept the proxy method invocations to inject authorization check.
* The original method is invoked through MethodProxy.
* @param object the proxy object
* @param method intercepted Method
* @param args arguments of the method
* @param proxy the proxy used to invoke the original method
* @throws Throwable any exception may be thrown; if so, super method will not be invoked
* @return any value compatible with the signature of the proxied method.
*/
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy ) throws Throwable {
if (authorizationService != null) {
//may throw an AuthorizationException if authorization failed
authorizationService.authorize(method);
}
return methodProxy.invokeSuper(object, args);
}
}
在intercept方法中,先檢查授權,如果授權通過,那么intercept方法呼叫目標物件的方法,由于性能原因,我們使用CGLIB的net.sf.cglib.proxy.MethodProxy物件而不是一般的java.lang.reflect.Method反射物件來呼叫原始方法,
使用CallbackFilter
net.sf.cglib.proxy.CallbackFilter允許你在方法級別設定回呼,假設你有一個PersistenceServiceImpl類,它有兩個方法:save和load,save方法需要進行授權檢查,而load方法不需要,
package com.lizjason.cglibproxy.impl;
import com.lizjason.cglibproxy.PersistenceService;
/**
* A simple implementation of PersistenceService interface
*
* @author Jason Zhicheng Li ([email protected])
*/
public class PersistenceServiceImpl implements PersistenceService {
public void save(long id, String data) {
System.out.println(data + " has been saved successfully.");
}
public String load(long id) {
return "Jason Zhicheng Li";
}
}
PersistenceServiceImpl類實作了PersistenceService介面,但這個不是必須的,PersistenceServiceImpl的net.sf.cglib.proxy.CallbackFilter實作如下:
package com.lizjason.cglibproxy.impl;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackFilter;
/**
* An implementation of CallbackFilter for PersistenceServiceImpl
*
* @author Jason Zhicheng Li ([email protected])
*/
public class PersistenceServiceCallbackFilter implements CallbackFilter {
//callback index for save method
private static final int SAVE = 0;
//callback index for load method
private static final int LOAD = 1;
/**
* Specify which callback to use for the method being invoked.
* @method the method being invoked.
* @return the callback index in the callback array for this method
*/
public int accept(Method method) {
String name = method.getName();
if ("save".equals(name)) {
return SAVE;
}
// for other methods, including the load method, use the
// second callback
return LOAD;
}
}
accept方法將代理方法映射到回呼,方法回傳值是一個回呼物件陣列中的下標,下面是PersistenceServiceImpl的代理創建實作:
...
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersistenceServiceImpl.class);
CallbackFilter callbackFilter = new PersistenceServiceCallbackFilter();
enhancer.setCallbackFilter(callbackFilter);
AuthorizationService authorizationService = ...
Callback saveCallback = new AuthorizationInterceptor(authorizationService);
Callback loadCallback = NoOp.INSTANCE;
Callback[] callbacks = new Callback[]{saveCallback, loadCallback };
enhancer.setCallbacks(callbacks);
...
return (PersistenceServiceImpl)enhancer.create();
在例子中,AuthorizationInterceptor應用于save方法,NoOp.INSTANCE應用于load方法,你可以通過net.sf.cglib.proxy.Enhancer.setInterfaces(Class[])指明代理需要實作的介面,但這個不是必須的,
對于net.sf.cglib.proxy.Enhancer,除了設定一個回呼物件陣列,你也可以使用net.sf.cglib.proxy.Enhancer.setCallbackTypes(Class[])設定一個回呼型別陣列,在代理創建程序中如果你沒有實際的回呼物件,那么這種方法非常有用,像回呼物件一樣,你也需要使用net.sf.cglib.proxy.CallbackFilter來指明每個攔截方法的回呼型別下標,你可以 關注公眾號:程式零世界 下載完整的樣例代碼,
總結
CGLIB是一個強大的高性能的代碼生成庫,作為JDK動態代理的互補,它對于那些沒有實作介面的類提供了代理方案,在底層,它使用ASM位元組碼操縱框架,本質上來說,CGLIB通過產生子類覆寫非final方法來進行代理,它比使用Java反射的JDK動態代理方法更快,CGLIB不能代理一個final類或者final方法,通常來說,你可以使用JDK動態代理方法來創建代理,對于沒有介面的情況或者性能因素,CGLIB是一個很好的選擇,
如果本文有寫的不對的地方歡迎評論指導,還可以關注公眾號:程式零世界 獲取更多原始碼資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/173494.html
標籤:Java
下一篇:&&和&、||和|的異同
