写cglib动态代理需要哪些jar包

写cglib动态代理需要哪些jar包,第1张

实现cglib动态代理需要4个jar包:
asm-223,
asm-commons-223,
asm-util-223,
cglib-nodep-21_3

字节码 *** 作包,用于动态生成代理类之类的 *** 作,类似常见的Javassist 包,具体的可以看>如果要使用Spring的aop特性,类就必须转换为Proxy,让Spring去管理切入点,jdk和cglib的性能差别不大,但是各有自己的限制:
JDK dynamic proxies:The classhasto implement interfaces Otherwise you will get ClassCastExceptions saying that $Proxy0 can not be casted to the particular class
Eventually dynamic proxies force you to program to interfaces since you can not cast the proxy to the class – a feature Ireallylike about them
�0�2CGLib proxies:
The proxies are created by sub-classing the actual class This means wherever an instance of the class is used it is also possible to use the CGLib proxy
The class needs to provide a default constructor, ie without any arguments Otherwise you’ll get an IllegalArgumentException: Superclass has no null constructors but no arguments were given This makes constructor injection impossible
The proxying does not work with final methods since the proxy sub class can not override the class’ implementation
The CGLib proxy is final, so proxying a proxy does not work You will get an IllegalArgumentException saying Cannot subclass final class $Proxy0″ But this feature is usually not needed anyway (Thisissuemight be solved in the future)
Since two objects are created (the instance of the class and the proxy as instance of a sub class) the constructor is called twice In general this should not matter I consider changing the class’ state based on constructor calls a code smell anyway
You have CGLib as additional dependency
如果你的类继承了某个父类,或者实现了某个接口,因为Spring没有办法判断这个是jdk自带的接口,还是你自己实现的接口,所以Spring就默认使用jdk proxy了,这样子类必须要实现了一个接口,然后用这个接口来调用该类,某则就会报:
$Proxy0 cannot be cast to xxx
之类的错误,但是也可以通过强制指定使用cglib,用下面的语句:
�0�2�0�2�0�2 <aop:scoped-proxy proxy-target-class=true /</bean这样子就可以强制使用cglib,也可以直接cast该类了,当然这不是一种好习惯,实现自己的接口在测试和替换的时候毕竟比较灵活。

扩展:

JDK生成代理类

ProxyClassFactory

CGLIB动态代理

JDK动态代理和Gglib动态代理的区别:

1JDK动态代理是实现了被代理对象的接口,Cglib是继承了被代理对象。

2JDK和Cglib都是在运行期生成字节码,JDK是直接写Class字节码,Cglib使用ASM框架写Class字节码,Cglib代理实现更复杂, 生成代理类比JDK效率低

3JDK调用代理方法,是通过反射机制调用,Cglib是通过FastClass机制直接调用方法,Cglib执行效率更高。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/13405665.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-30
下一篇 2023-07-30

发表评论

登录后才能评论

评论列表(0条)

保存