转载自 Java动态代理之cglib
cglib是对jdk动态代理的补充,弥补了因没有接口的类生成代理类的缺失。
下面通过简单的例子学习一下cglib的使用,当然,要是用需要第三方的jar包,jar包自行下载。
业务类
public class BankService {public void save(){System.out.println("存钱...");}
}
业务增强类
public class ServiceEnhancer {public static void before(){System.out.println("检查钱是否完整无存");}public static void after(){System.out.println("如果有错,就回滚");}
}
import java.lang.reflect.Method;import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;public class CglibProxy implements MethodInterceptor{private Enhancer enhancer = new Enhancer();public Object getProxy(Class<?> clazz){//设置 需要创建子类的类enhancer.setSuperclass(clazz);enhancer.setCallback(this);return enhancer.create();//通过字节码技术创建子类实例}@Overridepublic Object intercept(Object obj, //目标类实例Method method, //目标类方法的反射对象Object[] args, //方法的动态入参MethodProxy proxy //代理类实例) throws Throwable {ServiceEnhancer.before();Object result = proxy.invokeSuper(obj, args);ServiceEnhancer.after();return result;}}
public class CglibDemo {public static void main(String[] args) {CglibProxy proxy = new CglibProxy();BankService bankservice = (BankService) proxy.getProxy(BankService.class);bankservice.save();//com.proxy.cglib.BankService$$EnhancerByCGLIB$$82923c9a@2e5d6d97//System.out.println(bankservice);}
}