java动态代理总结
一.cglib动态代理实现
1.使用:
1)使用Enhancer工具类创建代理类
Enhancer enhancer = new Enhancer();
enhancer.setCallback(this);
enhancer.setSuperclass(this.target.getClass());
Object proxy = enhancer.create();
2)编写代理回调:实现methodIntercepter接口重写intecpte方法
a. 实现 MethodInterceptor
b.重写intercept方法
public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy);
2.说明:
1.可代理类和接口
2.代理类并不需要直接持有被代理类的引用,只是提供一个回调方法,通过实现接口编写回调方法,回调方法为业务操作
3.原理:
生成的代理类字节码中继承或者实现被代理类,并且持有代理增强回调MethodIncepter对象,代理方法中调用incepter方法
二. jdk代理动态实现
1.使用:
1)Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h)创建代理类和代理类对象
2.编写代理回调:实现InvocationHandler接口,重写public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;方法
2.说明:
1) 只可以代理接口
2) 代理类并不需要直接持有被代理类的引用,只是提供一个回调方法,通过 实现接口编写回调方法,回调方法为业务操作
3.原理:
生成一个实现了被代理接口,并且继承了Proxy的类,因此只可以代理接口, 若代理类则创建代理时会报错。代理类中持有增强描述类InvocationHandler类的对象,调用invoke方法进行方法增强

浙公网安备 33010602011771号