cglib-动态代理
动态代理 - CGLIB
在pom中导入合适版本的jar包:https://mvnrepository.com/artifact/cglib/cglib
1、定义拦截器实现 MethodInterceptor 接口
在这里实现代理增强细节
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//目标方法调用前
System.out.println("begin time------" + System.currentTimeMillis());
//这里不要使用invoke, 可能会出现oom的情况
Object o1 = methodProxy.invokeSuper(o, objects);
//目标方法调用后
System.out.println("end time ------" + System.currentTimeMillis());
return o1;
}
2、被代理类
假定被代理类为CGsubject,该类有一个sayHello方法,执行方法在控制台打印“hello CGSubject”
public class CGsubject {
public void sayHello(){
System.out.println("hello CGSubject");
}
}
3、生成代理对象,执行代理逻辑
//创建增强器
Enhancer enhancer = new Enhancer();
//设置被代理类
enhancer.setSuperclass(CGsubject.class);
//设置代理类,该类必须实现 MethodInterceptor 接口
//class HelloInterceptor implements MethodInterceptor
enhancer.setCallback(new HelloInterceptor());
//使用增强器生成代理实例, 强制类型转换为被代理类
CGsubject cGsubject = (CGsubject)enhancer.create();
//使用代理实例调用目标方法
cGsubject.sayHello();