CGLIB動態代理模式的理解

CGLIB動態代理模式


CGLIB動態代理模式 是一種第三方的動態代理模式,咱們在使用這個代理模式的時候,須要導入三方jar包,以下:node

  1. asm-2.2.3.jar
  2. asm-commons-2.2.3.jar
  3. asm-util-2.2.3.jar
  4. cglib-nodep-2.1_3.jar

CGLIB動態代理模式不須要想JDK動態代理模式那樣使用接口,一個非抽象類就能夠,可是前提是這個非抽象類須要實現MethodInterceptor接口,並重寫intercept方法。咱們經過代碼來了解其實現原理。
//建立一個普通類
public class SayHello {
    public void say(String name) {
        System.out.println("您好," + name);
    }
}
//CGLIB動態代理類
public class CglibProxy implements MethodInterceptor {
    
    /**
     * 生成CGLIB代理對象
     * @param cls -Class類 須要被代理的真實對象
     * @return
     */
    public Object getProxy(Class cls) {
        //1.CGLIB enhancer加強類對象
        Enhancer en = new Enhancer();
        //2.設置加強類型
        en.setSuperclass(cls);
        //3.定義代理邏輯對象爲當前對象,要求當前對象實現 MethodInterceptor 接口
        en.setCallback(this);
        //生成代理對象並返回
        Object proxy = en.create();
        return proxy;
    }
    /**
     * 代理邏輯方法
     * 1.proxy 代理對象
     * 2.method 方法
     * 3.args 方法參數
     * 4.methodProxy 方法代理
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("調用代理對象以前的邏輯~");
        Object result = methodProxy.invokeSuper(proxy, args);
        System.out.println("調用代理對象以後的邏輯~");
        return result;
    }
}
//測試代碼
public class TestCglibProxy {
    public static void main(String[] args) {
        CglibProxy cglib = new CglibProxy();
        SayHello proxy = (SayHello) cglib.getProxy(SayHello.class);
        proxy.say("James");
    }
}

結果展現

圖片描述

相關文章
相關標籤/搜索