CGLIB代理基础

  本文意在讲解CGLIB的基础使用及基本原理。

一、CGLIB的基本原理:

  依赖ASM字节码工具,通过动态生成实现接口或继承类的类字节码,实现动态代理。

  针对接口,生成实现接口的类,即implements方式;针对类,生成继承父类的类,即extends方式。

二、为什么使用CGLIB?

  JDK的动态代理只能基于接口,有时候我们想基于类生成动态代理,这个时候CGLIB是一个选择。

没什么场景下是必须使用CGLIB生成类代理的(个人观点),如果有,可能是代码简洁,某些情况下性能较好。

  CGLIB基于类生成动态代理需要注意?(CGLIB生成的代理是继承类的)

  1.  final声明的类是不能被代理的;

  2.  类中的private,final方法不能被代理,static方法不生成代理方法。

二、使用方法:

  基础示例代码:

1public interface UserInterface { 2 boolean login(int userid); 3} 4public class UserInterfaceImpl implements UserInterface { 5 public boolean login(int userid) { 6 System.out.println("do Login!"); 7 return false; 8 } 9}

  1. 代理接口:

1public class CGlibProxy implements net.sf.cglib.proxy.InvocationHandler{ //这里的InvocationHandler是cglib包中的 2 private UserInterface ref; 3 public CGlibProxy(UserInterface ref){ 4 this.ref = ref; 5 } 6 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 7 System.out.println("before"); 8 method.invoke(ref, args); 9 System.out.println("after"); 10 return null; 11 } 12} 13public class Test { 14 public static void main(String[] args) throws IOException { 15 Enhancer en = new Enhancer(); 16 en.setSuperclass(UserInterface.class); 17 en.setCallback(new CGlibProxy(new UserInterfaceImpl())); 18 UserInterface interfaced = (UserInterface) en.create(); 19 interfaced.login(1); 20 } 21}

  代理接口和JDK的使用方法基本没啥区别,传入被代理实例对象,调用实例的对象的method方法。

  所以如果是代理接口,完全没必要使用CGLIB。

  2. 代理类:

1public class CGlibProxy implements MethodInterceptor{ 2 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 3 System.out.println("before"); 4 Object o = proxy.invokeSuper(obj, args); 5 System.out.println("after"); 6 return o; 7 } 8} 9public class Test { 10 public static void main(String[] args) throws IOException { 11 Enhancer en = new Enhancer(); 12 en.setSuperclass(UserInterfaceImpl.class); 13 en.setCallback(new CGlibProxy()); 14 UserInterface interfaced = (UserInterface) en.create(); 15 interfaced.login(1); 16 } 17}

  3. Callback接口

   Callback即代理方法,上述示例中MethodInterceptor就是Callback的子接口。Callback定义一个空接口,可以方便扩展。

   Enhancer中有两个设置Callback的方法: setCallback(Callback callback), setCallbacks(Callback[] callbacks)。

   你可能定义多个Callback,然后定义不同的代理行为,如下:

1public class LoginProxy implements MethodInterceptor{ 2 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 3 System.out.println("before login"); 4 proxy.invokeSuper(obj, args); 5 System.out.println("after loign"); 6 return null; 7 } 8} 9public class OtherProxy implements MethodInterceptor{ 10 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 11 System.out.println("before"); 12 proxy.invokeSuper(obj, args); 13 System.out.println("after"); 14 return null; 15 } 16}

    cglib代理只能调用一个代理方法,所以当设置多个Callback时,你还需要指定一个CallbackFilter,通过Method条件指定Callback,

    CallbackFilter接口:

1public interface CallbackFilter { 2 int accept(Method method); //返回值为指定的Callback数组的下标索引 3}

  示例: 

1public class Test { 2 public static void main(String[] args) throws IOException { 3 Enhancer en = new Enhancer(); 4 en.setSuperclass(UserInterfaceImpl.class); 5 en.setCallbacks(new Callback[]{new LoginProxy(),new OtherProxy()}); //callback数组 6 en.setCallbackFilter(new CallbackFilter() { 7 public int accept(Method method) { 8 if(method.getName().equals("login")){ 9 return 0; //索引为0 , 即 LoginProxy 10 } 11 return 1; // 索引为1, 即 OtherProxy 12 } 13 }); 14 UserInterfaceImpl interfaced = (UserInterfaceImpl) en.create(); 15 interfaced.login(1); 16 interfaced.other(); 17 } 18}

  4. MethodInterceptor:MethodInterceptor接口是Callback的子接口,最常用。

1public interface MethodInterceptorextends Callback {   //obj: 代理对象本身,即cglib生成的代理实例 //method: 被代理对象中的方法  //args:方法的参数  //proxy: 存储了代理类,也就是obj 2 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable; 3}

          如何调用被代理的目标方法?  

    MethodProxy的 invokeSuper(obj,args) 方法;obj就是 代理对象本身 ,args是对象参数;

    MethodProxy还有一个invoke(obj,args)方法;obj参数是被代理对象,没搞懂这个方法的意图,个人觉得没什么必要。

  5. NamingPolicy,自定义代理类名称,默认实现是DefaultNamingPolicy

1public interface NamingPolicy { 2 String getClassName(String prefix, String source, Object key, Predicate names); 3}

  6. GeneratorStrategy,字节码生成策略,默认实现是DefaultGeneratorStrategy

1public interface GeneratorStrategy { 2 byte[] generate(ClassGenerator cg) throws Exception; 3}

     你可以重写DefaultGeneratorStrategy中的方法来替换字节码生成器,也可以访问或修改生成的字节码,如下:

1Enhancer en = new Enhancer(); 2en.setStrategy(new DefaultGeneratorStrategy(){ 3 protected byte[] transform(byte[] b) throws Exception { 4 return b; //b 是生成的字节码 5 } 6 protected ClassGenerator transform(ClassGenerator cg) throws Exception { 7 return cg; //cg 是字节码生成器 8 } 9});

  7. interceptDuringConstruction,设置构造函数中的方法调用是否使用代理方法,默认为true。

         示例:

1public class UserInterfaceImpl implements UserInterface { 2 public UserInterfaceImpl(){ 3 login(1); //构造函数中调用方法 4 } 5 public boolean login(int userid) { 6 System.out.println("do Login!"); 7 return false; 8 } 9} 10public class Test { 11 public static void main(String[] args) throws IOException { 12 Enhancer en = new Enhancer(); 13 en.setInterceptDuringConstruction(true); 14 en.setSuperclass(UserInterfaceImpl.class); 15 en.setCallback(new LoginProxy()); 16 UserInterfaceImpl interfaced = (UserInterfaceImpl) en.create(); 17 interfaced.login(1); 18 } 19}

      运行测试代码,结果如下,即login方法被代理了两次。

   

   en.setInterceptDuringConstruction(false) 时,运行结果如下,即login方法被代理了一次

   

  8. 没有默认构造函数时创建代理的方法:  

1public class UserInterfaceImpl implements UserInterface { 2 public UserInterfaceImpl(String param){ 3 } 4 public boolean login(int userid) { 5 System.out.println("do Login!"); 6 return false; 7 } 8} 9public class Test { 10 public static void main(String[] args) throws IOException { 11 Enhancer en = new Enhancer(); 12 en.setSuperclass(UserInterfaceImpl.class); 13 en.setCallback(new LoginProxy()); 14 UserInterfaceImpl interfaced = (UserInterfaceImpl) en.create(new Class[]{String.class}, new Object[]{"name"}); //创建方法中指定构造函数的参数类型及对应的参数值 15 interfaced.login(1); 16 } 17}

三、cglib创建类代理的基本原理

  如果让你实现类代理? ----  难点在哪里?

  1. 创建代理的过程:

   根据各种参数生成缓存的key --> 生成代理类(先缓存获取,缓存没有则用ClassGenerator生成代理类存入缓存) --> 根据代理类构造器生成代理对象实例。

  2. 代理类对象:

      可以设置系统参数cglib.debugLocation,开启代理类存入文件,该参数为文件存储路径。

     示例代码: 

1public class UserInterfaceImpl implements UserInterface { 2 public boolean login(int userid) { 3 return false; 4 } 5} 6public class Test { 7 public static void main(String[] args) throws IOException { 8 System.setProperty("cglib.debugLocation", "E://test"); 9 Enhancer en = new Enhancer(); 10 en.setSuperclass(UserInterfaceImpl.class); 11 en.setCallback(new LoginProxy()); 12 en.create(); 13 } 14}

     运行后,test目录下会生成一些class文件,找到同包(自己的package)目录,反编译打开(用的luyten,比jdgui好用)

     为了方便看,删除了一些不必要的代码;

1package cglibproxy; 2import java.lang.reflect.*; 3import net.sf.cglib.proxy.*; 4import net.sf.cglib.core.*; 5public class UserInterfaceImpl$$EnhancerByCGLIB$$f2d3e293 extends UserInterfaceImpl implements Factory 6{private MethodInterceptor CGLIB$CALLBACK_0; 7 private static Object CGLIB$CALLBACK_FILTER; 8 private static final Method CGLIB$login$0$Method; 9 private static final MethodProxy CGLIB$login$0$Proxy;private static final Method CGLIB$equals$1$Method; 10 private static final MethodProxy CGLIB$equals$1$Proxy; 11 private static final Method CGLIB$toString$2$Method; 12 private static final MethodProxy CGLIB$toString$2$Proxy; 13 private static final Method CGLIB$hashCode$3$Method; 14 private static final MethodProxy CGLIB$hashCode$3$Proxy; 15 private static final Method CGLIB$clone$4$Method; 16 private static final MethodProxy CGLIB$clone$4$Proxy; 17 final boolean CGLIB$login$0(final int n) { 18 return super.login(n); 19 } 20 21 public final boolean login(final int n) { 22 MethodInterceptor cglib$CALLBACK_2; 23 MethodInterceptor cglib$CALLBACK_0; 24 if ((cglib$CALLBACK_0 = (cglib$CALLBACK_2 = this.CGLIB$CALLBACK_0)) == null) { 25 CGLIB$BIND_CALLBACKS(this); 26 cglib$CALLBACK_2 = (cglib$CALLBACK_0 = this.CGLIB$CALLBACK_0); 27 } 28 if (cglib$CALLBACK_0 != null) { 29 final Object intercept = cglib$CALLBACK_2.intercept((Object)this, UserInterfaceImpl$$EnhancerByCGLIB$$f2d3e293.CGLIB$login$0$Method, new Object[] { new Integer(n) }, UserInterfaceImpl$$EnhancerByCGLIB$$f2d3e293.CGLIB$login$0$Proxy); 30 return intercept != null && (boolean)intercept; 31 } 32 return super.login(n); 33 } 34}

    可以从反编译的代理类中看到:

      代理类继承了被代理类,Factory接口是cglib的内部接口,有兴趣的可以去看一下;

      代理类代理了两种方法,一种是被代理类(即我们自定义的方法),一种是Object中的4个方法(toString, equals, hashCode, clone);

      代理类针对每个方法,生成了两个方法(一个代理方法,一个原方法) (为什么这么做?想想MethodProxy.invokeSuper(),这里是一个关键点);

      代理类中的目标方法都使用了final声明,禁止继续被代理;

以上就是个人总结的cglib的一些基础,水平有限,有问题欢迎评论中指正,谢谢!

原创文章,转载请注明出处。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

JDK动态代理和Cglib的动态代理

最简单的是静态代理方法,即代理模式,这里就不多啰嗦了。。重点说一下JDK的动态代理和Cglib的动态代理吧先说JDK的,需要被代理的类需要有接口,否则无法实现package proxy.dynamic;public interface IBook {void add();}实现接口

CGLIB介绍与原理(通过继承的动态代理)

一、什么是CGLIB?CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。通常可以使用Java的动态代理创建代理,但当要代理的类没有实现接口或者为了更好的性能,CGLIB是一个好的选择。二、CGLIB原理CGLIB原理:动态生成一个要代理类的子类,子类重写要代理的类的所有不是final的

Spring的两种代理JDK和CGLIB的区别浅谈

一、原理区别:java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。而cglib动态代理是利用asm开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。1、如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP 2、如果目标对象实现了接口,可以