動態代理與AOP

一、有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)代理的架構圖如下
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章