目录
前言
由于静态代理会导致类爆炸,所以需要使用动态生成类。总共分为两种方法,分别为JDK与GCLIB。
一、JDK与CGLIB
JDK只可以代理接口。
CGLIB可以代理接口与类。
二、使用方法
1.JDK生成类
代码如下(示例):
args分别为
1.获取目标对象的类加载器
2.获取目标对象的公共接口
3.构建调用处理器
OrderDao proxyOrderDao = (OrderDao)Proxy.newProxyInstance( orderDao.getClass().getClassLoader(), orderDao.getClass().getInterfaces(), new OrderInvocationHander(orderDao));
构建调用处理器流程:实现 InvocationHandler,并在构造方法中传入目标对象为target。
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 添加的代码 Object invoke = method.invoke(target, args); // ... //有返回值的方法需要在这里返回 return invoke; }
2.CGLIB生成代理类
CGLIB既可以代理接口也可以代理类,底层使用继承实现,所以代理类不可以使用final修饰。
// 该对象是CGLIB核心对象
Enhancer enhancer = new Enhancer();
// 告诉CGLIB父类是谁与目标类是谁
enhancer.setSueprclass(UserService.class);
//设置回调(等同于JDK动态代理中的调用处理器 InvocationHandler)
//使用 MethodInterceptor接口
enhancer.setCallback(new TimerMethodInterceptor());
UserService userServiceProxy = (UserService) enhancer.create();
实现MethodInterceptor