AspectJ的表達式實例


Joinpoints

  連接點,通俗的講就是想要橫切的目標,這些目標包括方法(Method),構造器(Constructor),域(Field),異常(Exception),對象和類初始化(Object and class)

Pointcuts

  切點,就是定義的規則,這些規則用於匹配目標連接點,切點包括兩部分advice(怎么切),expression(規則表達式)

  

//表達式格式
execution(modifiers? ret-type? declaring-type? name(param) throws?)

以上所有部分除了returning type和name以及paramter之外都是可選的,returning類型決定了匹配的方法必須要有指定的返回類型,可以使用*表示任意返回類型
只有當方法返回指定類型時,完全限定的類名才會被匹配,name匹配方法名,可以使用*匹配全部或部分方法名
parameters匹配就復雜一下:() 匹配一個無形參的方法,(..)匹配任意數量的形參方法(0~n),(*)匹配帶一個任意類型的形參方法
(*,String)匹配帶兩個形參,第一個任意類型,第二個必須是String類型

  實例

 
         
execution(public * *(..)):任意public方法
execution(* set*(..)):方法名以set開頭的任意方法
execution(* com.xyz.service.AccountService.*(..)):AccountService 接口下的任意方法 
execution(* com.xyz.service..(..)):service包下的任意方法
execution(* com.xyz.service...(..)):service包或子包下的任意方法
execution(public void MyClass.myMethod(String)) :MyClass 類的myMethod方法,方法public訪問權限,void返回值,形參只有一個並為String類型
execution(void MyClass.myMethod(..)):MyClass 類的myMethod方法,任意訪問權限,返回值void,任意形參
execution(* MyClass.myMethod(..)):MyClass 類的myMethod方法,任意返回值,任意形參
execution(* MyClass.myMethod*(..)):MyClass 類的以myMethod開頭的方法,任意返回值,任意形參
execution(* MyClass.myMethod*(String,..)):MyClass 類的以myMethod開頭的方法,任意返回值,第一個形參類型是String
execution(* *.myMethod(..)):任意類下myMethod方法 execution(MyClass.new()):任意MyClass類的無參構造器
execution(MyClass.new(..)):任意MyClass類的任意有參構造器 execution(MyClass+.new(..)):任意MyClass或其子類構造器
execution(public * com.mycompany..*.*(..)):com.mycompany包下任意子包的所有類的所有public 方法

//Spring AOP只能切方法(也就是任意連接點中的方法),AspectJ可以切任意成員(任意連接點,包括類/對象初始化塊,field,方法,構造器)
within(com.xyz.service.*):service包下任意連接點
within(com.xyz.service..*):service包或子包下任意連接點
this(com.xyz.service.AccountService):AccountService接口的代理實現里的任意連接點
target(com.xyz.service.AccountService):目標對象實現了AccountService接口的任意連接點
args(java.io.Serializable):只有一個參數且參數在運行時是Serializable類型的任意連接點
@target(org.springframework.transaction.annotation.Transactional):目標對象有一個@Transactional注解任意連接點
@within(org.springframework.transaction.annotation.Transactional):目標對象的聲明類型有一個@Transactional注解任意連接點
@annotation(org.springframework.transaction.annotation.Transactional):執行方法有一個@Transactional注解的任意連接點
@args(com.xyz.security.Classified):只有一個參數且參數在運行時參數有@Classified注解的任意連接點
bean(tradeService):Spring bean 名稱是tradeService的任意連接點
bean(*Service):Spring bean的名稱以Service結尾的任意連接點
//表達式可以使用|| && !進行組合 在XML下就是 or and not
execution(* com.xyz.myapp.service..(..)) and this(service)//xml
execution(* com.xyz.myapp.service..(..)) && this(service)//java

 

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM