Spring AOP 通過order來指定順序


詳見:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt398

 

Spring中的事務是通過aop來實現的,當我們自己寫aop攔截的時候,會遇到跟spring的事務aop執行的先后順序問題,比如說動態切換數據源的問題,如果事務在前,數據源切換在后,會導致數據源切換失效,所以就用到了Order(排序)這個關鍵字.

        我們可以通過在@AspectJ的方法中實現org.springframework.core.Ordered 這個接口來定義order的順序,order 的值越小,說明越先被執行。比如代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Component
@Aspect
public  class  AspectJ4DataBase  implements  Ordered {
     //攔截所有的service操作
     @Pointcut ( "execution( * com.hc.shop.*.service.*.*(..))" )
     public  void  readMethod() {
     } // 匹配所有的讀取操作
 
     @Before ( "readMethod()" )
     public  void  onlyReadPre() {
         DataSourceContextHolder.setDataSourceType(DataSourceType.MYSQL);
         System.out.println( "數據庫切換MYSQL" );
     }
 
     @After ( "readMethod()" )
     public  void  onlyReadPast() {
         DataSourceContextHolder.setDataSourceType(DataSourceType.ORACLE);
         System.out.println( "數據庫切換回ORACLE" );
     }
 
     @Override
     public  int  getOrder() {
// TODO Auto-generated method stub
         return  1 ;
     }
}

    在事務配置的地方也配置order 字段,代碼如下:    

<!-- 注解方式配置事物 -->

1
< tx:annotation-driven  transaction-manager = "transactionManager"  order = "2" />

 

這樣就實現了我們自己寫的aop在事務介入之前就執行了!

 


免責聲明!

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



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