揭示 Spring AOP 的內部運作原理
在這篇文章中,我們將揭秘 Spring 中面向面向程式設計(AOP)的內部機制。重點將放在理解 AOP 如何實現日誌記錄等功能,這些功能通常被認為是一種「魔法」。透過瀏覽核心 Java 實現,我們將了解 Java 的反射、代理模式和註釋,而不是任何真正神奇的東西。
先決條件
- Java 核心代理程式 API
- 反射API
- 註解API
這些都是 java.lang.reflect、java.lang.annotation 和 javassist.util.proxy 套件的一部分。
核心機制
Spring AOP 的核心是代理物件、方法攔截器和反射的概念。此模式中的關鍵角色是 MethodHandler(或呼叫處理程序)。此處理程序透過攔截方法呼叫來控制代理物件的行為。當在代理上呼叫方法時,它會透過處理程序傳遞,其中可以透過反射對註釋進行內省。根據所應用的註釋,可以在異常之前、之後或異常時執行必要的邏輯(例如日誌記錄)。
分解它
- 代理對象:這些是動態建立的對象,代表您的實際業務對象,透過方法處理程序路由方法呼叫。
- 呼叫處理程序:這就是攔截的神奇之處。使用反射,處理程序可以檢查目標方法上存在的註釋並相應地改變行為。
- 自訂註釋:您可以定義自訂註釋,它們用作觸發日誌記錄、安全檢查或事務管理等附加功能的標記。
範例: 假設我們想要在某些方法執行之前和之後加入日誌記錄。我們可以使用 @BeforeMethod 和 @AfterMethod 註解方法,而不是到處硬編碼日誌記錄。我們的處理程序檢查此註釋的方法並動態添加適當的日誌記錄邏輯。
以下是我們範例中控制器和服務的類別。
WorkerController.java
package edu.pk.poc.aop.controller; import edu.pk.poc.aop.annotation.AfterMethod; import edu.pk.poc.aop.annotation.All; import edu.pk.poc.aop.annotation.BeforeMethod; import edu.pk.poc.aop.helper.ProxyFactory; import edu.pk.poc.aop.service.Worker; import edu.pk.poc.aop.service.WorkerService; import edu.pk.poc.aop.service.WorkerServiceImpl; public class WorkerController { WorkerService workerService = ProxyFactory.createProxy(WorkerServiceImpl.class); /** * This Method 1s annotated with @BeforeMethod and @AfterMethod, So the log statements * will be generated before and after method call. */ @BeforeMethod @AfterMethod public void engageFullTimeWorker() throws Exception { Worker fullTimeWorker = new Worker(); fullTimeWorker.setName("FullTime-Worker"); fullTimeWorker.setPartTime(false); fullTimeWorker.setDuration(9); workerService.doWork(fullTimeWorker); } /** * This Method is annotated with @All, So the log statements will be generated before and after method call * along with exception if raised. */ @All public void engagePartTimeWorker() throws Exception { Worker partTimeWorker = new Worker(); partTimeWorker.setName("PartTime-Worker"); partTimeWorker.setPartTime(true); partTimeWorker.setDuration(4); workerService.doWork(partTimeWorker); } }
WorkerServiceImpl.java
package edu.pk.poc.aop.service; import edu.pk.poc.aop.annotation.AfterMethod; public class WorkerServiceImpl implements WorkerService { /** * Here this method is annotated with only @AfterMethod, So only log statement * will be generated after method call */ @AfterMethod @Override public void doWork(Worker worker) throws Exception { if (worker.isPartTime()) { throw new Exception("Part time workers are not permitted to work."); } System.out.print("A full time worker is working for " + worker.getDuration() + " hours :: "); for (int i = 1; i < worker.getDuration(); i++) { System.out.print("* "); } System.out.println(); } }
Main.java 測試類別
package edu.pk.poc.aop.test; import edu.pk.poc.aop.controller.WorkerController; import edu.pk.poc.aop.helper.ProxyFactory; import edu.pk.util.Logger; public class Main { public static void main(String[] args) { WorkerController controller = ProxyFactory.createProxy(WorkerController.class); Logger logger = new Logger(); try { System.out.println("Testing @BeforeMethod and @AfterMethod"); System.out.println("-----------------------------------------"); controller.engageFullTimeWorker(); System.out.println("Testing @All"); System.out.println("-----------------------------------------"); controller.engagePartTimeWorker(); } catch (Exception e) { logger.error("Exception caught in Main class"); } } }
輸出
Testing @BeforeMethod and @AfterMethod ----------------------------------------- >>> Entering into edu.pk.poc.aop.controller.WorkerController.engageFullTimeWorker() A full time worker is working for 9 hours :: * * * * * * * * >>> Exiting from edu.pk.poc.aop.service.WorkerServiceImpl.doWork() >>> Exiting from edu.pk.poc.aop.controller.WorkerController.engageFullTimeWorker() Testing @All ----------------------------------------- >>> Entering into edu.pk.poc.aop.controller.WorkerController.engagePartTimeWorker() >>> Exception in edu.pk.poc.aop.controller.WorkerController.engagePartTimeWorker() Exception caught in Main class
它是如何運作的
當在代理物件上呼叫方法時,該呼叫會被處理程序攔截,處理程序使用反射來檢查目標方法上的所有註解。根據這些註釋,處理程序決定是否記錄方法進入/退出、記錄異常或完全跳過記錄。
以下是可視化它的方法:
- 執行前:記錄方法條目。
- 執行後:記錄方法退出或成功。
- 全部:記錄方法條目、方法條目以及引發的異常。 這種動態行為表明 Spring AOP 利用了核心 Java API,而不是使用一些神奇的技巧。
定義註解
package edu.pk.poc.aop.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AfterMethod { }
package edu.pk.poc.aop.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface BeforeMethod { }
package edu.pk.poc.aop.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface All { }
定義代理工廠
package edu.pk.poc.aop.helper; /** * The {@code ProxyFactory} class is responsible for creating proxy objects using the Javassist library. * It allows for dynamic generation of proxies for classes or interfaces, with support for method interception. */ public class ProxyFactory { /** * A Javassist ProxyFactory instance used to generate proxy classes. */ private static final javassist.util.proxy.ProxyFactory factory = new javassist.util.proxy.ProxyFactory(); /** * Creates a proxy object for the given class or interface. * If the class is an interface, the proxy implements the interface. * If it's a concrete class, the proxy extends the class. * * @param <T> the type of the class or interface for which the proxy is to be created * @param klass the {@code Class} object representing the class or interface to proxy * @return a proxy instance of the specified class or interface, or {@code null} if proxy creation fails */ public static <T> T createProxy(Class<T> klass) { if (klass.isInterface()) factory.setInterfaces(new Class[]{klass}); else factory.setSuperclass(klass); try { return (T) factory.create(new Class<?>[0], new Object[0], new AOPLoggingMethodHandler()); } catch (Exception e) { System.err.println(e.getMessage()); } return null; } }
定義 MethodHandler
package edu.pk.poc.aop.helper; import edu.pk.poc.aop.annotation.AfterMethod; import edu.pk.poc.aop.annotation.All; import edu.pk.poc.aop.annotation.BeforeMethod; import edu.pk.poc.aop.annotation.OnException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import edu.pk.util.Logger; import javassist.util.proxy.MethodHandler; public class AOPLoggingMethodHandler implements MethodHandler { private static final Logger logger = new Logger(); public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { if (proceed != null) { // Concrete Method Object result = null; String className = resolveClassName(self); try { if (isAnnotationPresent(thisMethod, BeforeMethod.class) || isAnnotationPresent(thisMethod, All.class)) { logger.info(">>> Entering into " + className + "." + thisMethod.getName() + "()"); } result = proceed.invoke(self, args); if (isAnnotationPresent(thisMethod, AfterMethod.class) || isAnnotationPresent(thisMethod, All.class)) { logger.info(">>> Exiting from " + className + "." + thisMethod.getName() + "()"); } } catch (Throwable t) { if (isAnnotationPresent(thisMethod, OnException.class) || isAnnotationPresent(thisMethod, All.class)) { logger.error(">>> Exception in " + className + "." + thisMethod.getName() + "()"); } throw t; } return result; } throw new RuntimeException("Method is Abstract"); } private boolean isAnnotationPresent(Method method, Class klass) { Annotation[] declaredAnnotationsByType = method.getAnnotationsByType(klass); return declaredAnnotationsByType != null && declaredAnnotationsByType.length > 0; } private String resolveClassName(Object self) { String className = self.getClass().getName(); if (className.contains("_$$")) { className = className.substring(0, className.indexOf("_$$")); } return className; } }
結論
Spring AOP 是一個用於橫切關注點的強大工具,但它並沒有做任何革命性的事情。它建立在反射和代理等核心 Java 概念之上,這些概念在語言本身中可用。透過理解這一點,您可以更好地理解 Spring 如何簡化這些底層機制以方便開發人員。
以上是揭示 Spring AOP 的內部運作原理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

HashMap在Java中通過哈希表實現鍵值對存儲,其核心在於快速定位數據位置。 1.首先使用鍵的hashCode()方法生成哈希值,並通過位運算轉換為數組索引;2.不同對象可能產生相同哈希值,導致衝突,此時以鍊錶形式掛載節點,JDK8後鍊錶過長(默認長度8)則轉為紅黑樹提升效率;3.使用自定義類作鍵時必須重寫equals()和hashCode()方法;4.HashMap動態擴容,當元素數超過容量乘以負載因子(默認0.75)時,擴容並重新哈希;5.HashMap非線程安全,多線程下應使用Concu

Optional能清晰表達意圖並減少null判斷的代碼噪音。 1.Optional.ofNullable是處理可能為null對象的常用方式,如從map中取值時可結合orElse提供默認值,邏輯更清晰簡潔;2.通過鍊式調用map實現嵌套取值,安全地避免NPE,任一環節為null則自動終止並返回默認值;3.filter可用於條件篩選,滿足條件才繼續執行後續操作,否則直接跳到orElse,適合輕量級業務判斷;4.不建議過度使用Optional,如基本類型或簡單邏輯中其反而增加複雜度,部分場景直接返回nu

處理Java中的字符編碼問題,關鍵是在每一步都明確指定使用的編碼。 1.讀寫文本時始終指定編碼,使用InputStreamReader和OutputStreamWriter並傳入明確的字符集,避免依賴系統默認編碼。 2.在網絡邊界處理字符串時確保兩端一致,設置正確的Content-Type頭並用庫顯式指定編碼。 3.謹慎使用String.getBytes()和newString(byte[]),應始終手動指定StandardCharsets.UTF_8以避免平台差異導致的數據損壞。總之,通過在每個階段

遇到java.io.NotSerializableException的核心解決方法是確保所有需序列化的類實現Serializable接口,並檢查嵌套對象的序列化支持。 1.給主類添加implementsSerializable;2.確保類中自定義字段對應的類也實現Serializable;3.用transient標記不需要序列化的字段;4.檢查集合或嵌套對像中的非序列化類型;5.查看異常信息定位具體哪個類未實現接口;6.對無法修改的類考慮替換設計,如保存關鍵數據或使用可序列化的中間結構;7.考慮改

JavaSocket編程是網絡通信的基礎,通過Socket實現客戶端與服務器間的數據交換。 1.Java中Socket分為客戶端使用的Socket類和服務器端使用的ServerSocket類;2.編寫Socket程序需先啟動服務器監聽端口,再由客戶端發起連接;3.通信過程包括連接建立、數據讀寫及流關閉;4.注意事項包括避免端口衝突、正確配置IP地址、合理關閉資源及支持多客戶端的方法。掌握這些即可實現基本的網絡通信功能。

在Java中,Comparable用於類內部定義默認排序規則,Comparator用於外部靈活定義多種排序邏輯。 1.Comparable是類自身實現的接口,通過重寫compareTo()方法定義自然順序,適用於類有固定、最常用的排序方式,如String或Integer。 2.Comparator是外部定義的函數式接口,通過compare()方法實現,適合同一類需要多種排序方式、無法修改類源碼或排序邏輯經常變化的情況。兩者區別在於Comparable只能定義一種排序邏輯且需修改類本身,而Compar

遍歷Java中的Map有三種常用方法:1.使用entrySet同時獲取鍵和值,適用於大多數場景;2.使用keySet或values分別遍歷鍵或值;3.使用Java8的forEach簡化代碼結構。 entrySet返回包含所有鍵值對的Set集合,每次循環獲取Map.Entry對象,適合頻繁訪問鍵和值的情況;若只需鍵或值,可分別調用keySet()或values(),也可在遍歷鍵時通過map.get(key)獲取值;Java8中可通過Lambda表達式使用forEach((key,value)->

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,
