Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring AOP 的兩種代理:JDK 動態代理與 CGLIB

在動手實作 AOP 之前,先理解 Spring 背後用的是哪兩種代理機制,後面的行為才不會來得莫名其妙。

三條規則先記住:

  1. 目標物件有實作介面時,預設使用 JDK 動態代理。
  2. 有實作介面時,也可以強制改用 CGLIB。
  3. 目標物件沒有實作介面時,必須使用 CGLIB;Spring 會在兩者之間自動轉換。

效能上,JDK 動態代理單次執行速度較快,但 CGLIB 整體性能較佳,因此單例情境通常建議用 CGLIB。

一、JDK 動態代理(底層是反射)

public interface TestService {
    public int add();
}

public class TestServiceImpl implements TestService {
    @Override
    public int add() {
        System.out.println("開始執行 add...");
        return 0;
    }
}

代理類別要實作 InvocationHandler,注意 import 的是 java.lang.reflect.*:

public class JDKDynamicProxy implements InvocationHandler {

    // 被代理的目標物件
    private Object proxyObj;

    /**
     * Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
     * loader    : 類別載入器,決定代理物件由哪個 ClassLoader 載入
     * interfaces: 代理物件要宣稱實作的介面集合(多型)
     * h        : 方法被呼叫時要委派到哪個 InvocationHandler
     */
    public Object newProxy(Object proxyObj) {
        this.proxyObj = proxyObj;
        return Proxy.newProxyInstance(
                proxyObj.getClass().getClassLoader(),
                proxyObj.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
                                throws Throwable {
        before();
        Object object = method.invoke(this.proxyObj, args);  // 反射呼叫目標方法
        after();
        return object;
    }

    public void before() { System.out.println("執行目標物件之前..."); }
    public void after()  { System.out.println("執行目標物件之後..."); }
}
public static void main(String[] args) {
    TestService testService = new TestServiceImpl();  // 真實物件
    JDKDynamicProxy proxy = new JDKDynamicProxy();
    TestService testServiceProxy =
        (TestService) proxy.newProxy(testService);
    testServiceProxy.add();  // 執行代理物件的方法
}

二、CGLIB 代理

需要引入 cglib-nodep-2.1_3.jar。CGLIB 是一個高效能的位元碼生成庫,能在執行期擴充 Java 類別與實作介面。它的特色是不需要介面:

public class TestCGLIBServiceImpl {
    public int add() {
        System.out.println("開始執行 add...");
        return 0;
    }
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGLIBProxy implements MethodInterceptor {

    private Object targetObject;  // 被代理的目標物件

    public Object createProxyInstance(Object targetObject) {
        this.targetObject = targetObject;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetObject.getClass());  // 設定代理父類
        enhancer.setCallback(this);                    // 設定回呼
        return enhancer.create();
    }

    @Override
    public Object intercept(Object object, Method method, Object[] args,
                         MethodProxy methodproxy) throws Throwable {
        Object result = null;
        try {
            System.out.println("前置處理開始...");
            result = methodproxy.invoke(targetObject, args);
            System.out.println("後置處理開始...");
        } catch (Exception e) {
            System.out.println("異常處理...");
        } finally {
            System.out.println("呼叫結束...");
        }
        return result;
    }
}
public static void main(String[] args) {
    TestCGLIBServiceImpl target = new TestCGLIBServiceImpl();
    CGLIBProxy proxy = new CGLIBProxy();
    TestCGLIBServiceImpl proxyObj =
        (TestCGLIBServiceImpl) proxy.createProxyInstance(target);
    proxyObj.add();
}

寫在最後

程式碼只是入門。真要理解 Spring AOP,還是得回到原理:JDK 的反射與 newProxyInstance(...)、CGLIB 的 Enhancer 與 invoke() 到底做了什麼。下一篇就來看註解式的具體實作。

延伸閱讀:Spring AOP 進行日誌記錄、使用 Spring AOP 進行效能監控、利用 Spring AOP 更新 Memcached 快取策略。

Copyright © Linux教程網 All Rights Reserved