Cglib動態代理實現原理.md

1. 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非常瞭解,包括類文件格式和指令集

image

上圖展示了CGLIB庫相關框架以及語言之間的關係。另外提醒下,類似於Spring AOP和Hibernate這些框架它們經常同時使用CGLIB和JDK動態代理來滿足各自需要。Hibernate使用JDK動態代理爲WebShere應用服務實現一個事務管理適配器;Spring AOP則默認使用JDK動態代理來代理接口,除非你強制使用CGLIB

2. Cglib API

CGLIB庫的代碼量不多,但是由於缺乏文檔導致學習起來比較困難,CGLIB庫組織如下所示:

net.sf.cglib.beans:JavaBean相關的工具類
net.sf.cglib.core:底層字節碼操作類;大部分與ASP相關
net.sf.cglib.proxy:代理創建類、方法攔截類
net.sf.cglib.reflect:更快的反射類、C#風格的代理類
net.sf.cglib.transform:編譯期、運行期的class文件轉換類
net.sf.cglib.util:集合排序工具類

對於創建動態代理,大部分情況下你只需要使用proxy包的一部分API即可

上面已經提到,CGLIB庫是基於ASM的上層應用。對於代理沒有實現接口的類,CGLIB非常實用。本質上來說,對於需要被代理的類,它只是動態生成一個子類以覆蓋非final的方法,同時綁定鉤子回調自定義的攔截器。值得說的是,它比JDK動態代理還要快

image

CGLIB庫中經常用來代理類的API關聯圖如上所示。net.sf.cglib.proxy.Callback只是一個用於標記的接口,net.sf.cglib.proxy.Enhancer使用的所有回調都會繼承這個接口。

net.sf.cglib.proxy.MethodInterceptor是最常用的回調類型,在基於代理的AOP實現中它經常被用來攔截方法調用。這個接口只有一個方法:

public Object intercept(Object obj, 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方法中,自定義代碼可以在原始方法調用前或調用後注入。

image

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來創建代理吧。

3. 簡單代理

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[])。該方法的第一個參數指明參數類型,第二個參數指明參數值。參數中的原子類型需要使用包裝類

4. 使用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])
 */
public 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反射對象來調用原始方法

5. 使用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來指明每個攔截方法的回調類型下標

6. 總結

CGLIB是一個強大的高性能的代碼生成庫。作爲JDK動態代理的互補,它對於那些沒有實現接口的類提供了代理方案。在底層,它使用ASM字節碼操縱框架。本質上來說,CGLIB通過產生子類覆蓋非final方法來進行代理。它比使用Java反射的JDK動態代理方法更快。CGLIB不能代理一個final類或者final方法。通常來說,你可以使用JDK動態代理方法來創建代理,對於沒有接口的情況或者性能因素,CGLIB是一個很好的選擇

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章