二.cglib实现动态代理
程序员文章站
2022-06-18 11:22:28
...
实现cglib动态代理需要导入jar包,我这里是从spring项目中直接拿过来的com.springsource.net.sf.cglib-2.1.3.jar
看代码
package com.lzzl.cglibproxy;
public class Person {
public void doSomething(){
System.out.println("dosomething");
}
}
package com.lzzl.cglibproxy;
import java.lang.reflect.Method;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class cglibProxyFactory implements MethodInterceptor{
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodproxy) throws Throwable {
Object result;
if(proxy instanceof Person){
if("doSomething".equals(method.getName())){
System.out.println("doSomething 前");
result = methodproxy.invokeSuper(proxy, args);
System.out.println("doSomething 后");
return result;
}
}
return methodproxy.invokeSuper(proxy, args);
}
public Object createProxy(Class clazz){
//这里是为了生成字节码文件到指定文件夹下面
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E:\\work\\myeclipsework\\DynamicProxy\\generateFile\\cglib");
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
}
测试下
package com.lzzl.cglibproxy;
public class runcglibproxytest {
public static void main(String[] args) {
cglibProxyFactory proxyfc = new cglibProxyFactory();
Person proxy = (Person) proxyfc.createProxy(Person.class);
proxy.doSomething();
}
}
打印:
CGLIB debugging enabled, writing to ‘E:\work\myeclipsework\DynamicProxy\generateFile\cglib’
doSomething 前
dosomething
doSomething 后
生成的文件如下
生成的文件有很多,所以在项目中一般如果是单例类的话使用cglib动态代理的比较多。