一、SayHello
/**
* 被代理类,使用cglib可以不必实现接口
*/
public class SayHello {
public void say() {
System.out.println("success");
}
}
二、Cglib
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class Cglib implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class<?> clazz){
// 设置需要创建子类的类
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
// 通过字节码技术动态创建子类实例
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("前置代理");
// 通过代理类调用父类的方法
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("后置代理");
return invoke;
}
}
三、ProxyTest
public class ProxyTest {
public static void main(String[] args) {
Cglib cglib = new Cglib();
SayHello sayHello = (SayHello) cglib.getProxy(SayHello.class);
sayHello.say();
}
}