Spring AOP中pointcut expression表達式解析 及匹配多個條件


Spring中事務控制相關配置:

  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  </bean> 

  <tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
      <tx:method name="insert*" rollback-for="Exception"/>
      <tx:method name="update*" rollback-for="Exception"/>
      <tx:method name="delete*" rollback-for="Exception"/>
    </tx:attributes>
  </tx:advice>

  <aop:config>
    <aop:pointcut id="dbServiceOperation" expression="execution(* com.htt..*Service.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="dbServiceOperation"/>
  </aop:config>

  其中的“aop:pointcut”標簽中"expression"的寫法規則如下:

     execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)  throws-pattern?)

    方法中參數說明

    modifiers-pattern 可選參數 (public ,private,proteced)等 。

    ret-type-pattern  標識方法的返回值,需要使用全路徑的類名如java.lang.String,也可以為*表示任何返回值;

    declaring-type-pattern 可選參數

    name-pattern(param-pattern)是必須的.

    name-pattern:指定方法名,*代表所有,例如set*,代表以set開頭的所有方法.
    param-pattern:指定方法參數(聲明的類型),(..)代表所有參數,(*)代表一個參數,(*,String)代表第一個參數為任何值,第二個為String類型.

    表達式例子如下:

  任意公共方法的執行:
    execution(public * *(..))
  任何一個以“set”開始的方法的執行:
    execution(* set*(..))
  AccountService 接口的任意方法的執行:
    execution(* com.xyz.service.AccountService.*(..))
  定義在service包里的任意方法的執行:
    execution(* com.xyz.service.*.*(..))
  定義在service包和所有子包里的任意類的任意方法的執行:
    execution(* com.xyz.service..*.*(..))
  定義在pointcutexp包和所有子包里的JoinPointObjP2類的任意方法的執行:
    execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")

  在多個表達式之間使用 ||,or表示 或,使用 &&,and表示 與,!表示 非.例如:

     <aop:config>
      <aop:pointcut id="pointcut" expression="(execution(* com.ccboy.dao..*.find*(..))) or (execution(* com.ccboy.dao..*.query*(..)))"/>
      <aop:advisor advice-ref="jdbcInterceptor" pointcut-ref="pointcut" />
  </aop:config>


免責聲明!

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



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