CG Lib动态代理
CG Lib代理的对象无需实现接口
目标对象
package com.life.cglib; public class UserDao{ public void save() { System.out.println("保存数据"); } }
代理工厂
package com.life.cglib; 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 ProxyFactory implements MethodInterceptor{ private Object target;//维护一个目标对象 public ProxyFactory(Object target) { this.target = target; } //为目标对象生成代理对象 public Object getProxyInstance() { //工具类 Enhancer en = new Enhancer(); //设置父类 en.setSuperclass(target.getClass()); //设置回调函数 en.setCallback(this); //创建子类对象代理 return en.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("开启事务"); // 执行目标对象的方法 Object returnValue = method.invoke(target, args); System.out.println("关闭事务"); return null; } }
测试类
package com.life.cglib; import org.junit.Test; public class TestProxy { @Test public void testCglibProxy(){ //目标对象 UserDao target = new UserDao(); System.out.println(target.getClass()); //代理对象 UserDao proxy = (UserDao) new ProxyFactory(target).getProxyInstance(); System.out.println(proxy.getClass()); //执行代理对象方法 proxy.save(); } }