CGLIB动态代理
ReflectServiceImpl类
public class ReflectServiceImpl {
public void sayHello(String name){
System.out.println("Hello" + name);
}
}
CglibProxyExample.class
public class CglibProxyExample implements MethodInterceptor {
/**
* 生产CGLIB对象
* @param cls--Class类
* @return Class类的CGLIB代理对象
*/
public Object getProxy(Class cls){
//CGLIB enhancer增强类对象
Enhancer enhancer = new Enhancer();
//设置增强类型
enhancer.setSuperclass(cls);
//定义代理逻辑对象为当前对象,要求当前对象实现MethodInterceptpr方法
enhancer.setCallback(this);
//生产并返回代理对象
return enhancer.create();
}
/**
* 代理逻辑方法
* @param proxy 代理对象
* @param method 方法
* @param args 方法参数
* @param methodProxy 方法代理
* @return 代理逻辑返回
* @throws Throwable 异常
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("调用真实对象前");
//CGLIB反射调用真实对象方法
Object result = methodProxy.invokeSuper(proxy, args);
System.out.println("调用真实对象后");
return result;
}
}
testCGLIBProxy.class
public class testCGLIBProxy {
public static void main(String[] args) {
testCGLIBProxy();
}
public static void testCGLIBProxy(){
CglibProxyExample cpe = new CglibProxyExample();
ReflectServiceImpl obj = (ReflectServiceImpl) cpe.getProxy(ReflectServiceImpl.class);
obj.sayHello("张三");
}
}
JDK动态代理必须提供接口才能使用,在一些不能提供接口的环境中,可以采用CGLIB动态代理,它的优势是不需要提供接口,只有一个非抽象类就能实现动态代理