方法內部之間調用的攔截

下面是CGLib的原生寫法(使用net.sf.cglib.proxy.*包內的類實現)

class Foo {
    public void fun1(){
        System.out.println("fun1");
        fun2();
    }
    public void fun2() {
        System.out.println("fun2");
    }
}

class CGlibProxyEnhancer implements MethodInterceptor{
    public Object getProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.print("before ");
        Object result = proxy.invokeSuper(obj,args);
        return result;
    }
}

public class Test {
    public static void main(String[] args) {
        CGlibProxyEnhancer pf = new CGlibProxyEnhancer();
        Foo foo = (Foo) pf.getProxy(Foo.class);
        foo.fun1();
    }
}

打印結果是:
before fun1
before fun2
可以看到,雖然fun2()是通過foo.fun1()調用的,但fun()2依然能被代理。

但如果用Spring AOP那套基本寫法的話:

class Foo {
    public void fun1() {
        System.out.println("fun1");
        fun2();
    }
    public void fun2() {
        System.out.println("fun2");
    }
}
class Before implements MethodBeforeAdvice {

    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.print("before ");
    }
}

public class TestCGLib {
    public static void main(String[] args) {
        Foo foo = new Foo();
        BeforeAdvice advice = new Before();
        ProxyFactory pf = new ProxyFactory();
        pf.setOptimize(true);//啓用Cglib2AopProxy創建代理
        pf.setProxyTargetClass(true);
        pf.setTarget(foo);
        pf.addAdvice(advice);
        Foo proxy = (Foo) pf.getProxy();
        proxy.fun1();
    }
}

輸出結果是:
before fun1
fun2
可見fun2方法沒有被代理。

 

這個帖子中還說到了如何將cglib中的fun2改爲private則最終結果與常規AOP的一樣.

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