Cglib动态代理
程序员文章站
2023-12-29 23:32:34
...
package javaDesignModule.cglibproxy;
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 Object targetObj;
/**
* 创建代理对象
* @param obj
* @return
*/
public Object getInstance(Object obj) {
this.targetObj = obj;
Enhancer enhancer = new Enhancer();//用这个类创建代理对象(对代理类的子类)
enhancer.setSuperclass(targetObj.getClass());//设置被代理类作为其父类
enhancer.setCallback(this);//设置回调 当代理对象的方法被调用时 回调方法intercept()会被执行
return enhancer.create();//返回创建的代理对象
}
@Override
public Object intercept(Object targetObj, Method method, Object[] arg2, MethodProxy mp) throws Throwable {
Object obj = null;
try {
before();
//调用cglib的代理对象 所属的父类被代理的方法
obj = mp.invokeSuper(targetObj, arg2);
after();
} catch (Exception e) {
e.printStackTrace();
//记录日志
}
return obj;
}
/**
* 身份验证
*/
public void before(){
System.out.println("前置增强--------------");
}
public void after(){
System.out.println("后置增强..." );
}
}
package javaDesignModule.cglibproxy;
import javaDesignModule.staticproxy.TicketManager;
import javaDesignModule.staticproxy.TicketManagerImpl;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
CglibProxy cglibProxy = new CglibProxy();
TicketManager tm = (TicketManager) cglibProxy.getInstance(new TicketManagerImpl());
tm.soldTicket();
tm.changeTicket();
tm.returnTicket();
}
}
个人借鉴前辈的代码,勿喷
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 Object targetObj;
/**
* 创建代理对象
* @param obj
* @return
*/
public Object getInstance(Object obj) {
this.targetObj = obj;
Enhancer enhancer = new Enhancer();//用这个类创建代理对象(对代理类的子类)
enhancer.setSuperclass(targetObj.getClass());//设置被代理类作为其父类
enhancer.setCallback(this);//设置回调 当代理对象的方法被调用时 回调方法intercept()会被执行
return enhancer.create();//返回创建的代理对象
}
@Override
public Object intercept(Object targetObj, Method method, Object[] arg2, MethodProxy mp) throws Throwable {
Object obj = null;
try {
before();
//调用cglib的代理对象 所属的父类被代理的方法
obj = mp.invokeSuper(targetObj, arg2);
after();
} catch (Exception e) {
e.printStackTrace();
//记录日志
}
return obj;
}
/**
* 身份验证
*/
public void before(){
System.out.println("前置增强--------------");
}
public void after(){
System.out.println("后置增强..." );
}
}
package javaDesignModule.cglibproxy;
import javaDesignModule.staticproxy.TicketManager;
import javaDesignModule.staticproxy.TicketManagerImpl;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
CglibProxy cglibProxy = new CglibProxy();
TicketManager tm = (TicketManager) cglibProxy.getInstance(new TicketManagerImpl());
tm.soldTicket();
tm.changeTicket();
tm.returnTicket();
}
}
个人借鉴前辈的代码,勿喷