Spring AOP 詳解(轉載)

 

轉載自 http://pandonix.iteye.com/blog/336873/


此前對於AOP的使用僅限於聲明式事務,除此之外在實際開發中也沒有遇到過與之相關的問題。最近項目中遇到了以下幾點需求,仔細思考之後,覺得采用AOP 來解決。一方面是爲了以更加靈活的方式來解決問題,另一方面是藉此機會深入學習Spring AOP相關的內容。本文是權當本人的自己AOP學習筆記,以下需求不用AOP肯定也能解決,至於是否牽強附會,仁者見仁智者見智。

  1. 對部分函數的調用進行日誌記錄,用於觀察特定問題在運行過程中的函數調用情況
  2. 監控部分重要函數,若拋出指定的異常,需要以短信或郵件方式通知相關人員
  3. 金控部分重要函數的執行時間

    事實上,以上需求沒有AOP也能搞定,只是在實現過程中比較鬱悶擺了。

  1. 需要打印日誌的函數分散在各個包中,只能找到所有的函數體,手動添加日誌。然而這些日誌都是臨時的,待問題解決之後應該需要清除打印日誌的代碼,只能再次手動清除^_^!
  2. 類 似1的情況,需要捕獲異常的地方太多,如果手動添加時想到很可能明天又要手動清除,只能再汗。OK,該需求相對比較固定,屬於長期監控的範疇,並不需求臨 時添加後再清除。然而,客戶某天要求,把其中20%的異常改爲短信提醒,剩下的80%改用郵件提醒。改之,兩天後,客戶抱怨短信太多,全部改成郵件提 醒...
  3. 該需求通常用於監控某些函數的執行時間,用以判斷系統執行慢的瓶頸所在。瓶頸被解決之後,煩惱同情況1


    終於下定決心,採用AOP來解決!代碼如下:

 

    切面類TestAspect

Java代碼  收藏代碼
  1. package com.spring.aop;  
  2. /** 
  3.  * 切面 
  4.  * 
  5.  */  
  6. public class TestAspect {  
  7.   
  8.     public void doAfter(JoinPoint jp) {  
  9.         System.out.println("log Ending method: "  
  10.                 + jp.getTarget().getClass().getName() + "."  
  11.                 + jp.getSignature().getName());  
  12.     }  
  13.   
  14.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
  15.         long time = System.currentTimeMillis();  
  16.         Object retVal = pjp.proceed();  
  17.         time = System.currentTimeMillis() - time;  
  18.         System.out.println("process time: " + time + " ms");  
  19.         return retVal;  
  20.     }  
  21.   
  22.     public void doBefore(JoinPoint jp) {  
  23.         System.out.println("log Begining method: "  
  24.                 + jp.getTarget().getClass().getName() + "."  
  25.                 + jp.getSignature().getName());  
  26.     }  
  27.   
  28.     public void doThrowing(JoinPoint jp, Throwable ex) {  
  29.         System.out.println("method " + jp.getTarget().getClass().getName()  
  30.                 + "." + jp.getSignature().getName() + " throw exception");  
  31.         System.out.println(ex.getMessage());  
  32.     }  
  33.   
  34.     private void sendEx(String ex) {  
  35.         //TODO 發送短信或郵件提醒  
  36.     }  
  37. }   

 

 

Java代碼  收藏代碼
  1. package com.spring.service;  
  2. /** 
  3.  * 接口A 
  4.  */  
  5. public interface AService {  
  6.       
  7.     public void fooA(String _msg);  
  8.   
  9.     public void barA();  
  10. }  
 
Java代碼  收藏代碼
  1. package com.spring.service;  
  2. /** 
  3.  *接口A的實現類 
  4.  */  
  5. public class AServiceImpl implements AService {  
  6.   
  7.     public void barA() {  
  8.         System.out.println("AServiceImpl.barA()");  
  9.     }  
  10.   
  11.     public void fooA(String _msg) {  
  12.         System.out.println("AServiceImpl.fooA(msg:"+_msg+")");  
  13.     }  
  14. }  

 

 

Java代碼  收藏代碼
  1. package com.spring.service;  
  2.   
  3. /** 
  4.  *   Service類B 
  5.  */  
  6. public class BServiceImpl {  
  7.   
  8.     public void barB(String _msg, int _type) {  
  9.         System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");  
  10.         if(_type == 1)  
  11.             throw new IllegalArgumentException("測試異常");  
  12.     }  
  13.   
  14.     public void fooB() {  
  15.         System.out.println("BServiceImpl.fooB()");  
  16.     }  
  17.   
  18. }  
 

    ApplicationContext

Java代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="  
  6.             http://www.springframework.org/schema/beans  
  7.             http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  8.             http://www.springframework.org/schema/aop  
  9.             http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"  
  10.     default-autowire="autodetect">  
  11.     <aop:config>  
  12.         <aop:aspect id="TestAspect" ref="aspectBean">  
  13.             <!--配置com.spring.service包下所有類或接口的所有方法-->  
  14.             <aop:pointcut id="businessService"  
  15.                 expression="execution(* com.spring.service.*.*(..))" />  
  16.             <aop:before pointcut-ref="businessService" method="doBefore"/>  
  17.             <aop:after pointcut-ref="businessService" method="doAfter"/>  
  18.             <aop:around pointcut-ref="businessService" method="doAround"/>  
  19.             <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>  
  20.         </aop:aspect>  
  21.     </aop:config>  
  22.       
  23.     <bean id="aspectBean" class="com.spring.aop.TestAspect" />  
  24.     <bean id="aService" class="com.spring.service.AServiceImpl"></bean>  
  25.     <bean id="bService" class="com.spring.service.BServiceImpl"></bean>  
  26.   
  27. </beans>  

 

    測試類AOPTest

Java代碼  收藏代碼
  1. public class AOPTest extends AbstractDependencyInjectionSpringContextTests {  
  2.       
  3.     private AService aService;  
  4.       
  5.     private BServiceImpl bService;  
  6.       
  7.     protected String[] getConfigLocations() {  
  8.         String[] configs = new String[] { "/applicationContext.xml"};  
  9.         return configs;  
  10.     }  
  11.       
  12.       
  13.     /** 
  14.      * 測試正常調用 
  15.      */  
  16.     public void testCall()  
  17.     {  
  18.         System.out.println("SpringTest JUnit test");  
  19.         aService.fooA("JUnit test fooA");  
  20.         aService.barA();  
  21.         bService.fooB();  
  22.         bService.barB("JUnit test barB",0);  
  23.     }  
  24.       
  25.     /** 
  26.      * 測試After-Throwing 
  27.      */  
  28.     public void testThrow()  
  29.     {  
  30.         try {  
  31.             bService.barB("JUnit call barB",1);  
  32.         } catch (IllegalArgumentException e) {  
  33.               
  34.         }  
  35.     }  
  36.       
  37.     public void setAService(AService service) {  
  38.         aService = service;  
  39.     }  
  40.       
  41.     public void setBService(BServiceImpl service) {  
  42.         bService = service;  
  43.     }  
  44. }  

 

    運行結果如下:

Java代碼  收藏代碼
  1. log Begining method: com.spring.service.AServiceImpl.fooA  
  2. AServiceImpl.fooA(msg:JUnit test fooA)  
  3. log Ending method: com.spring.service.AServiceImpl.fooA  
  4. process time: 0 ms  
  5. log Begining method: com.spring.service.AServiceImpl.barA  
  6. AServiceImpl.barA()  
  7. log Ending method: com.spring.service.AServiceImpl.barA  
  8. process time: 0 ms  
  9. log Begining method: com.spring.service.BServiceImpl.fooB  
  10. BServiceImpl.fooB()  
  11. log Ending method: com.spring.service.BServiceImpl.fooB  
  12. process time: 0 ms  
  13. log Begining method: com.spring.service.BServiceImpl.barB  
  14. BServiceImpl.barB(msg:JUnit test barB type:0)  
  15. log Ending method: com.spring.service.BServiceImpl.barB  
  16. process time: 0 ms  
  17.   
  18. log Begining method: com.spring.service.BServiceImpl.barB  
  19. BServiceImpl.barB(msg:JUnit call barB type:1)  
  20. log Ending method: com.spring.service.BServiceImpl.barB  
  21. method com.spring.service.BServiceImpl.barB throw exception  
  22. 測試異常  
 

    《Spring參考手冊》中定義了以下幾個AOP的重要概念,結合以上代碼分析如下:

  • 切面(Aspect) :官方的抽象定義爲“一個關注點的模塊化,這個關注點可能會橫切多個對象”,在本例中,“切面”就是類TestAspect所關注的具體行爲,例如,AServiceImpl.barA()的調用就是切面TestAspect所關注的行爲之一。“切面”在ApplicationContext中<aop:aspect>來配置。
  • 連接點(Joinpoint) :程序執行過程中的某一行爲,例如,AServiceImpl.barA()的調用或者BServiceImpl.barB(String _msg, int _type)拋出異常等行爲。
  • 通知(Advice) :“切面”對於某個“連接點”所產生的動作,例如,TestAspect中對com.spring.service包下所有類的方法進行日誌記錄的動作就是一個Advice。其中,一個“切面”可以包含多個“Advice”,例如TestAspect
  • 切入點(Pointcut) :匹配連接點的斷言,在AOP中通知和一個切入點表達式關聯。例如,TestAspect中的所有通知所關注的連接點,都由切入點表達式execution(* com.spring.service.*.*(..))來決定
  • 目標對象(Target Object) :被一個或者多個切面所通知的對象。例如,AServcieImpl和BServiceImpl,當然在實際運行時,Spring AOP採用代理實現,實際AOP操作的是TargetObject的代理對象。
  • AOP代理(AOP Proxy) 在Spring AOP中有兩種代理方式,JDK動態代理和CGLIB代理。默認情況下,TargetObject實現了接口時,則採用JDK動態代理,例如,AServiceImpl;反之,採用CGLIB代理,例如,BServiceImpl。強制使用CGLIB代理需要將 <aop:config> 的 proxy-target-class 屬性設爲true

       通知(Advice)類型

  • 前置通知(Before advice) :在某連接點(JoinPoint)之前執行的通知,但這個通知不能阻止連接點前的執行。ApplicationContext中在<aop:aspect>裏面使用<aop:before>元素進行聲明。例如,TestAspect中的doBefore方法
  • 後通知(After advice) :當某連接點退出的時候執行的通知(不論是正常返回還是異常退出)。ApplicationContext中在<aop:aspect>裏面使用<aop:after>元素進行聲明。例如,TestAspect中的doAfter方法,所以AOPTest中調用BServiceImpl.barB拋出異常時,doAfter方法仍然執行
  • 返回後通知(After return advice) :在某連接點正常完成後執行的通知,不包括拋出異常的情況。ApplicationContext中在<aop:aspect>裏面使用<after-returning>元素進行聲明。
  • 環繞通知(Around advice) :包圍一個連接點的通知,類似Web中Servlet規範中的Filter的doFilter方法。可以在方法的調用前後完成自定義的行爲,也可以選擇不執行。ApplicationContext中在<aop:aspect>裏面使用<aop:around>元素進行聲明。例如,TestAspect中的doAround方法。
  • 拋出異常後通知(After throwing advice) : 在方法拋出異常退出時執行的通知。 ApplicationContext中在<aop:aspect>裏面使用<aop:after-throwing>元素進行聲明。例如,TestAspect中的doThrowing方法。

       切入點表達式

  • 通常情況下,表達式中使用”execution“就可以滿足大部分的要求。表達式格式如下:
Java代碼  收藏代碼
  1. execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)  

modifiers-pattern:方法的操作權限

ret-type-pattern:返回值

declaring-type-pattern:方法所在的包

name-pattern:方法名

parm-pattern:參數名

throws-pattern:異常

其中,除ret-type-pattern和name-pattern之外,其他都是可選的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值爲任意類型;方法名任意;參數不作限制的所有方法。

  • 通知參數

可以通過args來綁定參數,這樣就可以在通知(Advice)中訪問具體參數了。例如,<aop:aspect>配置如下

Java代碼  收藏代碼
  1. <aop:config>  
  2.     <aop:aspect id="TestAspect" ref="aspectBean">  
  3.         <aop:pointcut id="businessService"  
  4.             expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />  
  5.             <aop:after pointcut-ref="businessService" method="doAfter"/>  
  6.     </aop:aspect>  
  7. </aop:config>  

TestAspect的doAfter方法中就可以訪問msg參數,但這樣以來AService中的barA()和BServiceImpl中的barB()就不再是連接點,因爲execution(* com.spring.service.*.*(String,..))只配置第一個參數爲String類型的方法。其中,doAfter方法定義如下:

Java代碼  收藏代碼
  1. public void doAfter(JoinPoint jp,String msg)  
  •   訪問當前的連接點

任何通知(Advice)方法可以將第一個參數定義爲 org.aspectj.lang.JoinPoint 類型。JoinPoint 接口提供了一系列有用的方法, 比如 getArgs() (返回方法參數)、getThis() (返回代理對象)、getTarget() (返回目標)、getSignature() (返回正在被通知的方法相關信息)和 toString()(打印出正在被通知的方法的有用信息。


再次聲明,轉載自 http://pandonix.iteye.com/blog/336873/ 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章