spring的AOP的实现一种是使用原生的jdk的反射,一种就是使用cglib
引用一下:
CGlib是一个强大的,高性能,高质量的Code生成类库。它可以在运行期扩展Java类与实现Java接口。
使用的时候报了如下错误:
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
忘引入asm的包了,引入,报如下错误:
java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V
换了个asm-all的包。。通过...
hellowork
写一个代理类实现MethodIntercepter接口的intercept的方法,其中用proxy调用invokesuper的方法
接下来就是调用方法了,启用enhancer调用setsuperclass为要代理的类,setcallback为调用的代理类,然后用enhancer调用create重新生成一个要代理的类就ok了。
1 2 3 4 5 6 7 8 9 10 11 | public class TestCglib { public static void main(String[] args) { //HelloWord helloWord=new HelloWord(); //helloWord.sayHello(); Enhancer enhancer= new Enhancer(); enhancer.setSuperclass(HelloWord. class ); enhancer.setCallback( new CglibProxy()); HelloWord helloWord=(HelloWord) enhancer.create(); helloWord.sayHello(); } } |
输出结果如下:
引用一个博客,里面的例子也很好。特别是增加了methodfilter,是的cglib的功能更强大了
http://llying.iteye.com/blog/220452
总结一下,cglib封装了asm可以对类进行动态代理。主要是实现一个proxy实现了MethodIntercepter接口,然后客户端使用enhancer调用setsuperclass和setcallback,也可以用setcallbackfilter来过滤某些方法。
联系客服