cgkib动态代理详解-不依赖接口,速度快

1. cglib原理-不依赖接口,速度快

使用ASM字节框架动态生成要代理类的子类,子类重写final以外的方法,织入横切逻辑

2. 示例-实现MethodInterceptor

Test.java
public class Test {
    public  void sayHello(String ss){
        System.out.println(ss);
    }
}
TargetInterceptor.java
public class TargetInterceptor implements MethodInterceptor {
    public  Object getInstance(Object source){
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(source.getClass());
        //设置回调方法
        enhancer.setCallback(this);
        //创建代理对象
        return enhancer.create();
    }

    /**
     * 重写方法拦截在方法前和方法后加入业务
     * Object obj为目标对象
     * Method method为目标方法
     * Object[] params 为参数,
     * MethodProxy proxy CGlib方法代理对象
     */
    public Object intercept(Object obj, Method method, Object[] params,
                            MethodProxy proxy) throws Throwable {
        System.out.println("调用前");
        Object result = proxy.invokeSuper(obj, params);
        System.out.println(" 调用后"+result);
        return result;
    }

    public static void main(String[] args) {
        Test test = new Test();
        Test proxy = (Test)new TargetInterceptor().getInstance(test);
        System.out.println("proxy类型:"+proxy.getClass().getName());
        proxy.sayHello("zzzzzzz");
    }
}

执行结果

proxy类型:test.java.cglibtest.Test$$EnhancerByCGLIB$$6926e63
调用前
zzzzzzz
 调用后null
posted @ 2017-07-29 14:28  Desneo  阅读(300)  评论(0编辑  收藏  举报