SSM9.1【Spring:面向切面程式設計AOP-Spring的AOP簡介】
阿新 • • 發佈:2021-07-21
概述
JDK的動態代理
1 package com.haifei.proxy.jdk; 2 3 /** 4 * 目標類介面 5 */ 6 public interface TargetInterface { 7 8 public void save(); 9 10 }
1 package com.haifei.proxy.jdk; 2 3 /** 4 * 目標類 5 */ 6 public class Target implements TargetInterface{ 7 8 @Override9 public void save() { 10 System.out.println("save running..."); 11 } 12 13 }
1 package com.haifei.proxy.jdk; 2 3 /** 4 * 增強類 5 */ 6 public class Advice { 7 8 public void before(){ 9 System.out.println("前置增強。。。"); 10 } 11 12 public void after(){ 13 System.out.println("後置增強。。。");14 } 15 16 }
1 package com.haifei.proxy.jdk; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 /** 8 * JDK 的動態代理-測試類 9 * 10 * 動態代理參考: 11 * JavaWeb19.6【Filter&Listener:利用設計模式之代理模式增強物件的功能】 12 *https://www.cnblogs.com/yppah/p/14974136.html 13 */ 14 public class ProxyTest { 15 16 public static void main(String[] args) { 17 //目標物件 18 final Target target = new Target(); 19 //增強物件 20 final Advice advice = new Advice(); 21 22 //獲取動態生成的代理物件 23 TargetInterface proxy = (TargetInterface)Proxy.newProxyInstance( 24 target.getClass().getClassLoader(), //目標物件類載入器 25 target.getClass().getInterfaces(), //目標物件相同的介面位元組碼物件陣列 26 new InvocationHandler() { 27 //呼叫代理物件的任何方法 實質執行的都是invoke方法 28 @Override 29 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 30 advice.before(); //前置增強 31 Object invoke = method.invoke(target, args); //執行目標方法 32 advice.after(); //後置增強 33 return invoke; 34 } 35 } 36 ); 37 38 //呼叫代理物件的方法 39 proxy.save(); 40 } 41 /* 42 前置增強。。。 43 save running... 44 後置增強。。。 45 */ 46 47 }