Spring AOP中pointcut expression表示式解析及匹配多個條件
原文地址:http://www.cnblogs.com/qinyubin/p/4075466.html
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?)
ret-type-pattern,name-pattern(param-pattern)是必須的.
ret-type-pattern:標識方法的返回值,需要使用全路徑的類名如java.lang.String,也可以為*表示任何返回值;
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>