下面是CGLib的原生寫(xiě)法(使用net.sf.cglib.proxy.*包內(nèi)的類實(shí)現(xiàn))
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();
}
}
打印結(jié)果是:
before fun1
before fun2
可以看到,雖然fun2()是通過(guò)foo.fun1()調(diào)用的,但fun()2依然能被代理。
但如果用Spring AOP那套基本寫(xiě)法的話:
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創(chuàng)建代理
pf.setProxyTargetClass(true);
pf.setTarget(foo);
pf.addAdvice(advice);
Foo proxy = (Foo) pf.getProxy();
proxy.fun1();
}
}
輸出結(jié)果是:
before fun1
fun2
可見(jiàn)fun2方法沒(méi)有被代理。
為什么會(huì)有這樣的差異?
spring的aop無(wú)法攔截內(nèi)部方法調(diào)用,spring 會(huì)報(bào)存真實(shí)對(duì)象的 bean 以及 代理后的 proxyBean,proxyBean進(jìn)行了切面增強(qiáng)處理:
proxyBean 相當(dāng)于:
before
invoke(bean,method)
after
這樣處理就導(dǎo)致實(shí)際上 fun2 是實(shí)際的 bean 去調(diào)用的(invoke就是使用實(shí)際對(duì)象執(zhí)行你要執(zhí)行的方法),所以,沒(méi)有 before 效果。
而你實(shí)際使用 cglib 則全程都是用的是代理 bean