被代理的类如果实现接口,那么使用JDK的代理模式,设计到Proxy,InvocationHandler。
如果被代理的类没有实现接口,那么使用CGLIB来实现代理。
此类没有实现接口,要代理此类,只能使用CGLIB:
CGLIB代理的模式:
测试方法:
如果被代理的类没有实现接口,那么使用CGLIB来实现代理。
此类没有实现接口,要代理此类,只能使用CGLIB:
public class Operation {
private String name;
public Operation(){}
public Operation(String name){
this.name = name;
}
public void doInsert(String name) {
System.out.println(" 操作完成 ");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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 CGLIBProxyFactory implements MethodInterceptor{
private Object delegate;
public Object createProxyInstance(Object delegate){
this.delegate = delegate;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.delegate.getClass());//代理类会生产一个被代理类的子类,final方法除外
enhancer.setCallback(this);//将本身设为回调对象,必须实现接口MehtoInterceptor
return enhancer.create();
}
//代理对象被回调的时候调用此方法
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
Operation operation = (Operation)this.delegate;
Object result = null;
if (operation.getName()!=null) {
System.out.println("开始...");
result = methodProxy.invoke(delegate, args);
System.out.println("结束...");
}
return result;
}
}
测试方法:
public class Test {
public static void main(String[] args) {
CGLIBProxyFactory cFactory = new CGLIBProxyFactory();
Operation operation = (Operation)cFactory.createProxyInstance(new Operation("老李"));
operation.doInsert("XXX");
}
}