cglib动态代理演示
public class CglibProxyFactory {
public static Object getProxy(Class<?> clazz) {
Enhancer enhancer = new Enhancer();
enhancer.setClassLoader(clazz.getClassLoader());
enhancer.setSuperclass(clazz);
enhancer.setCallback(new DebugMethodInterceptor());
return enhancer.create();
}
}
public class DebugMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("前置方法执行" + method.getName());
Object object = methodProxy.invokeSuper(o, args);
System.out.println("后置方法执行" + method.getName());
return object;
}
}
public class AService {
public String send(String message) {
System.out.println("a send message:" + message);
return message;
}
}
public class TestMain {
public static void main(String[] args) {
AService proxy = (AService) CglibProxyFactory.getProxy(AService.class);
proxy.send("发送消息");
}
}
前置方法执行send
a send message:发送消息
后置方法执行send
进程已结束,退出代码为 0