在 Spring AOP 中,aop:pointcut 的 expression 是決定哪些方法被攔截的關鍵。它通常使用 AspectJ 語法,以 execution 為核心,描述方法簽名。
一個常見寫法是:
execution(* com.abc..biz..*.add*(..))
它可以拆成幾個部分:
因此,這個表達式會匹配 com.abc 底下任意層級 biz 套件中,類別名稱任意、方法名以 add 開頭的方法。
execution 的完整概念可理解為:修飾符、回傳型別、宣告型別、方法名、參數與例外。其中回傳型別、方法名與參數型別是核心。ret-type-pattern 可用 * 表示任意回傳;name-pattern 可用 * 或 set* 等;參數部分可用 (..) 表示任意參數,(*) 表示單一參數,(*, String) 表示第一個參數任意、第二個為 String。
可以分別定義新增、修改、刪除的切入點,再讓同一個通知方法套用:
aop:pointcut id="pointcut_add" expression="execution(* com.abc..biz..*.add*(..))" aop:pointcut id="pointcut_update" expression="execution(* com.abc..biz..*.update*(..))" aop:pointcut id="pointcut_delete" expression="execution(* com.abc..biz..*.delete*(..))"
然後在 aop:aspect 中以 pointcut-ref 引用,讓日誌通知在這些方法執行後觸發。
JoinPoint 代表連接點,可在通知中取得方法執行時的上下文:
透過 JoinPoint,通知可以取得方法名稱、參數與目標資訊,非常適合用來做日誌、稽核或效能記錄。