动态代理与AOP

来源:互联网 发布:淘宝pv uv 率 编辑:程序博客网 时间:2024/05/19 02:27

一、有2种方式生成代理对象
(1)

static Class getProxyClass(ClassLoader,Class,interface);

(2)

static Object
newProxyInstance(ClassLoader,ClassInterface,InvocationHandler n)

二、动态代理与AOP

 (1) 使用第二种代理方式进行代理 (2) InvocationHandler类MyInvocationHandler,实现invoke方法 //实现InvocationHandler接口 因为newProxyInstance方法中有InvocationHandler参数 public class MyInvocationHandler implements InvocationHandler(){      //目标对象(需要被代理的对象)                public Object target;      public void setTarget(Object target){           this.target = target;      }      //重写Invoke方法      @override      public Object Invoke(Object proxy, Method method, Object[] args) throws Throwable {              //实例化增强类           Extend extend = new Extend();           //前置执行 模拟Spring AOP            extend.ExtendMethod1();           //执行目标方法  target为被代理的对象           Object result = method.invoke(target,args);           //后置执行           extend.ExtendMethod2();           return result;      } } //代理生成工厂MyProxyFactory public class MyProxyFactory(){     //获取目标对象的代理对象       public static Object getProxy(Object target){           //实例化MyInvocationHandler并将目标对象导入           MyInvocationHandler myInvocationHandler = new MyInvocationHandler();           myInvocationHandler.setTarget(target);          //生成代理对象           Object result= Proxy.newProxyInstance(target.getClass().getClassLoader(),           target.getClass().getInterfaces(),myInvocationHandler);           return result;      }      //使用      public static void main(String[] args){           Person zs = new ZhangSan();           Person zsproxy = MyProxyFactory.getProxy(zs);           zsproxy.say();//      } }

增强方法1
我是张三—–》walk
增强方法2

三、总结
(1)Proxy类主要方法有四个(如下图),jdk动态代理主要是利用Proxy类的getProxyClass和newProxyInstance方法生成接口的动态代理对象,并将执行代理对象的每个方法时都被替换执行InvocationHandler对象的Invoke方法。这为spring的aop打好了基础。此外,实际应用中,我们一般不会单纯直接生成一个(或多个)接口的代理对象,而是生成某个接口实现类(目标类)的代理对象。
这里写图片描述

(2)代理的架构图如下
这里写图片描述