文章目錄
- 一、切入表達式簡介
- 二、切入表達式的語法
- 1. 方法匹配符
- 示例:
- 2. 類型匹配符
- 示例:
一、切入表達式簡介
切入表達式(Pointcut Expression)是AOP中定義切入點(Pointcut)的一種方式。它定義了在哪些連接點(Join Point)上應用通知(Advice)。在Spring Boot中,切入表達式主要用于:
- 定義切入點:指定在哪些方法或類上應用通知。
- 精確匹配:使用通配符和邏輯運算符精確匹配目標方法。
切入表達式通常與通知類型(Advice Type)一起使用,如前置通知、后置通知、環繞通知等,以實現橫切關注點的模塊化管理。
二、切入表達式的語法
1. 方法匹配符
-
execution(modifiers-pattern? return-type-pattern declaring-type-pattern? method-name-pattern(param-pattern) throws-pattern?)
- modifiers-pattern:方法的訪問修飾符,如
public
、protected
、private
等。 - return-type-pattern:方法的返回類型,如
void
、具體的類名等。 - declaring-type-pattern:方法所在類的全限定名或包名模式。
- method-name-pattern:方法名,支持通配符匹配。
- param-pattern:方法的參數模式,如
(..)
表示任意參數,(String, ..)
表示第一個參數為String類型,其余任意類型參數。 - throws-pattern:方法可能拋出的異常模式。
- modifiers-pattern:方法的訪問修飾符,如
示例:
-
匹配所有
Service
接口的所有方法:execution(* com.example.service.*.*(..))
-
匹配所有返回類型為
String
的方法:execution(String com.example.service.*.*(..))
2. 類型匹配符
除了execution
,還有其他類型的切入點表達式:
within
:匹配指定類型內的所有方法。target
:匹配指定目標對象類型的方法調用。args
:匹配傳入參數類型符合指定條件的方法。
示例:
-
匹配所有
@Service
注解類中的方法:@within(org.springframework.stereotype.Service) && execution(* *(..))
-
匹配所有以
Service
結尾的類及其子包下的方法:within(com.example.service..*) && execution(* *(..))