cglib实现动态代理
代理逻辑
package cn.chen.proxy.cglibproxy;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class TransCglibProxy implements MethodInterceptor{
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("transacation start");
methodProxy.invokeSuper(obj, args);
System.out.println("transacation commit");
return null;
}
}
测试
package cn.chen.proxy.cglibproxy
import cn.chen.proxy.jdk.UserMgr
import cn.chen.proxy.jdk.UserMgrImpl
import net.sf.cglib.proxy.Enhancer
public class TestCglib {
public static void main(String[] args) {
TransCglibProxy proxy =new TransCglibProxy()
//委托类
UserMgr userMgr = new UserMgrImpl()
Enhancer enhancer = new Enhancer()
enhancer.setSuperclass(userMgr.getClass())
enhancer.setCallback(proxy)
//代理类
UserMgr proxyUser = (UserMgr) enhancer.create()
proxyUser.addUser()
}
}