Spring 之 Cglib (动态代理)

  • Post author:
  • Post category:其他




Spring 之 Cglib (动态代理)

Cglib 的FastClass 会比一般的java的动态代理快很多。下面代码中有简单的说明

/**
 * @ClassName TargetPojo
 * @Author 莫邪
 * @Description TODO
 * @Date Created in 0:17 2020/4/8
 * @Version 1.0
 */
//被代理的类
public class TargetPojo {

    public void pojoMethod(){
        System.out.println("TargetPojo pojoMethod run");
    }
}
/**
 * @ClassName DefaultMethodInterceptor
 * @Author 莫邪
 * @Description TODO
 * @Date Created in 0:38 2020/4/8
 * @Version 1.0
 */
//默认的代理方法实现接口,cglib 定义被代理后会执行的接口方法
public class DefaultMethodInterceptor implements MethodInterceptor {
    private Object target;//被代理对象
    public DefaultMethodInterceptor(Object target){
        this.target =target;
    }
    @Override
    public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(proxy.getClass());//生成的代理类
        System.out.println(methodProxy.getSuperName());
        before(method);
//        Object res = method.invoke(target, objects);
        Object res = methodProxy.invokeSuper(proxy,objects);//直接执行父类的方法不走反射 FastClas优化 为代理类和被代理类都生成来了一个,要执行的方法直接通过索引下标去导航(耗内存,但是快)
        return res;
    }

    private void before(Method method){
        System.out.println("before method:" + method.getName());
    }
}

/**
 * @ClassName CglibUtil
 * @Author 莫邪
 * @Description TODO
 * @Date Created in 0:22 2020/4/8
 * @Version 1.0
 */
//Cglib 代理工具类
public class CglibUtil {

    public static  <E>E getCglibProxy(E target, MethodInterceptor methodInterceptor){
//        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\class");//输出生成的代理类,可以用于分析
        if(methodInterceptor==null){
            methodInterceptor= new DefaultMethodInterceptor(target);
        }
        E o =(E) Enhancer.create(target.getClass(), methodInterceptor);
        return o;

    }

}

/**
 * @ClassName CglibEg1
 * @Author 莫邪
 * @Description TODO
 * @Date Created in 0:18 2020/4/8
 * @Version 1.0
 */
//cglib使用案例
public class CglibEg1 {
    public static void main(String[] args) {

        TargetPojo proxy = CglibUtil.getCglibProxy(new TargetPojo(), null);
        proxy.pojoMethod();
        System.out.println("打印生成的代理类");
        Method[] methods = proxy.getClass().getMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
}



版权声明:本文为weixin_36927395原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。