cglib动态代理的主要组成
MethodInterceptor 接口的实现类
被代理的类(不用必须实现接口,但是不能是final的,final类不能被继承,所以不能被代理)
Enhancer 类设置代理关系
代码
实现MethodInterceptor接口的类
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibCallBackInvocationHandler implements MethodInterceptor {
private Object target;
public CglibCallBackInvocationHandler(Object target) {
this.target = target;
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib before do ....");
Object result = method.invoke(target, objects);
System.out.println("cglib after do ......");
return result;
}
}
被代理的类
public class TargetAction {
private String info;
public TargetAction(){
}
public TargetAction(String info){
this.info=info;
}
public String doSomething(){
System.out.println("cglib do proxy "+ info);
return "proxy "+info;
}
}
测试类
public class CglibDemo {
public static void main(String[] args) {
TargetAction targetAction = new TargetAction("demo1");
CglibCallBackInvocationHandler handler = new CglibCallBackInvocationHandler(targetAction);
Enhancer enhancer = new Enhancer();
//设置代理什么类
enhancer.setSuperclass(targetAction.getClass());
//设置invoker
enhancer.setCallback(handler);
TargetAction result = (TargetAction) enhancer.create();
String proxyResult = result.doSomething();
System.out.println(proxyResult);
}
}
https://blog.csdn.net/goodwell__/article/details/105930337