轉載請註明來源-作者@loongshawn:http://blog.csdn.net/loongshawn/article/details/72303040,建議讀者閱讀原文,確保獲得完整的信息
1.execution表達式
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.loongshawn.method.ces..*.*(..))" />
<aop:aspect ref="logAspect">
<aop:before pointcut-ref="pointcut" method="beforeAdvice"/>
<aop:after-returning pointcut-ref="pointcut" arg-names="joinPoint,retValue" returning="retValue" method="afterAdvice"/>
</aop:aspect>
</aop:config>
上述配置爲AOP配置代碼片段,其中expression部分爲定義切點的表達式部分,如下:
execution(* com.loongshawn.method.ces..*.*(..))
注意:markdown中符號“*”是加粗,因此輸出“*”符號需要進行轉義“*”。
表達式結構解釋如下:
標識符 | 含義 |
---|---|
execution() | 表達式的主體 |
第一個“*”符號 | 表示返回值的類型任意 |
com.loongshawn.method.ces | AOP所切的服務的包名,即,需要進行橫切的業務類 |
包名後面的“..” | 表示當前包及子包 |
第二個“*” | 表示類名,*即所有類 |
.*(..) | 表示任何方法名,括號表示參數,兩個點表示任何參數類型 |
2.官方文檔介紹
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern)
throws-pattern?)
上述表達式結構是Spring官方文檔說明,翻譯爲中文如下,其中除了返回類型模式、方法名模式和參數模式外,其它項都是可選的。
execution(<修飾符模式>?<返回類型模式><方法名模式>(<參數模式>)<異常模式>?)
接下來,結合官方文檔中的例子從不同的維度來了解execution表達式。表達式上方的中文說明爲對該表達式的解釋,請注意閱讀方式。
維度1.通過方法修飾符定義切點
匹配所有的public修飾符的方法:
execution(public * *(..))
維度2.通過方法名定義切點
匹配所有”set”開頭的方法:
execution(* set*(..))
維度3.通過類定義切點
匹配AccountService 接口的所有方法:
execution(* com.xyz.service.AccountService.*(..))
維度4.通過包定義切點
匹配service包中的所有方法:
execution(* com.xyz.service..(..))
匹配service包及其子包中的所有方法:
execution(* com.xyz.service...(..))
維度5.通過方法入參定義切點
切點表達式中方法入參部分比較複雜,可以使用”*”和“..”通配符,其中“*”表示任意類型的參數,而“..”表示任意類型參數且參數個數不限。
匹 配joke(String,int)方法,且joke()方法的第一個入參是String,第二個入參是int。如果方法中的入參類型是Java.lang包下的類,可以直接使用類名,否則必須使用全限定類名,如joke(java.util.List,int);
execution(* joke(String,int))
匹 配目標類中的joke()方法,該方法第一個入參爲String,第二個入參可以是任意類型,如joke(Strings1,String s2)和joke(String s1,double d2)都匹配,但joke(String s1,doubled2,String s3)則不匹配;
execution(* joke(String,*))
匹配目標類中的joke()方法,該方法第 一個入參爲String,後面可以有任意個入參且入參類型不限,如joke(Strings1)、joke(String s1,String s2)和joke(String s1,double d2,Strings3)都匹配。
execution(* joke(String,..))
匹 配目標類中的joke()方法,方法擁有一個入參,且入參是Object類型或該類的子類。它匹配joke(Strings1)和joke(Client c)。如果我們定義的切點是execution(*joke(Object)),則只匹配joke(Object object)而不匹配joke(Stringcc)或joke(Client c)。
execution(* joke(Object+))
3.官方文檔截圖
Aspect Oriented Programming with Spring–>11.2.3 Declaring a pointcut
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
- 另增加:
函數參數
.. 匹配任類型意參數個數(包括沒有)
* 匹配單個任意類型參數
方法參數個數可以進行限制
例如:(*,..) 匹配1個或1個以上任意類型參數,
(*,*) 匹配兩個任意類型參數
本文僅對官方文檔做了翻譯及簡要說明,需要在實際使用過程中加深印象及理解。