轉(zhuǎn)自: http://pandonix.iteye.com/blog/336873
?
此前對(duì)于AOP的使用僅限于聲明式事務(wù),除此之外在實(shí)際開(kāi)發(fā)中也沒(méi)有遇到過(guò)與之相關(guān)的問(wèn)題。最近項(xiàng)目中遇到了以下幾點(diǎn)需求,仔細(xì)思考之后,覺(jué)得采用AOP 來(lái)解決。一方面是為了以更加靈活的方式來(lái)解決問(wèn)題,另一方面是借此機(jī)會(huì)深入學(xué)習(xí)Spring AOP相關(guān)的內(nèi)容。本文是權(quán)當(dāng)本人的自己AOP學(xué)習(xí)筆記,以下需求不用AOP肯定也能解決,至于是否牽強(qiáng)附會(huì),仁者見(jiàn)仁智者見(jiàn)智。
- 對(duì)部分函數(shù)的調(diào)用進(jìn)行日志記錄,用于觀察特定問(wèn)題在運(yùn)行過(guò)程中的函數(shù)調(diào)用情況
- 監(jiān)控部分重要函數(shù),若拋出指定的異常,需要以短信或郵件方式通知相關(guān)人員
- 金控部分重要函數(shù)的執(zhí)行時(shí)間
??? 事實(shí)上,以上需求沒(méi)有AOP也能搞定,只是在實(shí)現(xiàn)過(guò)程中比較郁悶擺了。
- 需要打印日志的函數(shù)分散在各個(gè)包中,只能找到所有的函數(shù)體,手動(dòng)添加日志。然而這些日志都是臨時(shí)的,待問(wèn)題解決之后應(yīng)該需要清除打印日志的代碼,只能再次手動(dòng)清除^_^!
- 類(lèi) 似1的情況,需要捕獲異常的地方太多,如果手動(dòng)添加時(shí)想到很可能明天又要手動(dòng)清除,只能再汗。OK,該需求相對(duì)比較固定,屬于長(zhǎng)期監(jiān)控的范疇,并不需求臨 時(shí)添加后再清除。然而,客戶(hù)某天要求,把其中20%的異常改為短信提醒,剩下的80%改用郵件提醒。改之,兩天后,客戶(hù)抱怨短信太多,全部改成郵件提 醒...
- 該需求通常用于監(jiān)控某些函數(shù)的執(zhí)行時(shí)間,用以判斷系統(tǒng)執(zhí)行慢的瓶頸所在。瓶頸被解決之后,煩惱同情況1
???
終于下定決心,采用AOP來(lái)解決!代碼如下:
?
??? 切面類(lèi)TestAspect
- package ?com.spring.aop;??
- /** ?
- ?*?切面 ?
- ?* ?
- ?*/ ??
- public ? class ?TestAspect?{??
- ??
- ???? public ? void ?doAfter(JoinPoint?jp)?{??
- ????????System.out.println( "log?Ending?method:?" ??
- ????????????????+?jp.getTarget().getClass().getName()?+? "." ??
- ????????????????+?jp.getSignature().getName());??
- ????}??
- ??
- ???? public ?Object?doAround(ProceedingJoinPoint?pjp)? throws ?Throwable?{??
- ???????? long ?time?=?System.currentTimeMillis();??
- ????????Object?retVal?=?pjp.proceed();??
- ????????time?=?System.currentTimeMillis()?-?time;??
- ????????System.out.println( "process?time:?" ?+?time?+? "?ms" );??
- ???????? return ?retVal;??
- ????}??
- ??
- ???? public ? void ?doBefore(JoinPoint?jp)?{??
- ????????System.out.println( "log?Begining?method:?" ??
- ????????????????+?jp.getTarget().getClass().getName()?+? "." ??
- ????????????????+?jp.getSignature().getName());??
- ????}??
- ??
- ???? public ? void ?doThrowing(JoinPoint?jp,?Throwable?ex)?{??
- ????????System.out.println( "method?" ?+?jp.getTarget().getClass().getName()??
- ????????????????+? "." ?+?jp.getSignature().getName()?+? "?throw?exception" );??
- ????????System.out.println(ex.getMessage());??
- ????}??
- ??
- ???? private ? void ?sendEx(String?ex)?{??
- ???????? //TODO?發(fā)送短信或郵件提醒 ??
- ????}??
- }???
package com.spring.aop; /** * 切面 * */ public class TestAspect { public void doAfter(JoinPoint jp) { System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName()); } public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long time = System.currentTimeMillis(); Object retVal = pjp.proceed(); time = System.currentTimeMillis() - time; System.out.println("process time: " + time + " ms"); return retVal; } public void doBefore(JoinPoint jp) { System.out.println("log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName()); } public void doThrowing(JoinPoint jp, Throwable ex) { System.out.println("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception"); System.out.println(ex.getMessage()); } private void sendEx(String ex) { //TODO 發(fā)送短信或郵件提醒 } }
?
?
- package ?com.spring.service;??
- /** ?
- ?*?接口A ?
- ?*/ ??
- public ? interface ?AService?{??
- ??????
- ???? public ? void ?fooA(String?_msg);??
- ??
- ???? public ? void ?barA();??
- }??
package com.spring.service; /** * 接口A */ public interface AService { public void fooA(String _msg); public void barA(); }
?
- package ?com.spring.service;??
- /** ?
- ?*接口A的實(shí)現(xiàn)類(lèi) ?
- ?*/ ??
- public ? class ?AServiceImpl? implements ?AService?{??
- ??
- ???? public ? void ?barA()?{??
- ????????System.out.println( "AServiceImpl.barA()" );??
- ????}??
- ??
- ???? public ? void ?fooA(String?_msg)?{??
- ????????System.out.println( "AServiceImpl.fooA(msg:" +_msg+ ")" );??
- ????}??
- }??
package com.spring.service; /** *接口A的實(shí)現(xiàn)類(lèi) */ public class AServiceImpl implements AService { public void barA() { System.out.println("AServiceImpl.barA()"); } public void fooA(String _msg) { System.out.println("AServiceImpl.fooA(msg:"+_msg+")"); } }
?
?
- package ?com.spring.service;??
- ??
- /** ?
- ?*???Service類(lèi)B ?
- ?*/ ??
- public ? class ?BServiceImpl?{??
- ??
- ???? public ? void ?barB(String?_msg,? int ?_type)?{??
- ????????System.out.println( "BServiceImpl.barB(msg:" +_msg+ "?type:" +_type+ ")" );??
- ???????? if (_type?==? 1 )??
- ???????????? throw ? new ?IllegalArgumentException( "測(cè)試異常" );??
- ????}??
- ??
- ???? public ? void ?fooB()?{??
- ????????System.out.println( "BServiceImpl.fooB()" );??
- ????}??
- ??
- }??
package com.spring.service; /** * Service類(lèi)B */ public class BServiceImpl { public void barB(String _msg, int _type) { System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")"); if(_type == 1) throw new IllegalArgumentException("測(cè)試異常"); } public void fooB() { System.out.println("BServiceImpl.fooB()"); } }
?
??? ApplicationContext
- <?xml?version= "1.0" ?encoding= "UTF-8" ?>??
- <beans?xmlns= "http://www.springframework.org/schema/beans" ??
- ????xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" ??
- ????xmlns:aop= "http://www.springframework.org/schema/aop" ??
- ????xsi:schemaLocation="??
- ????????????http: //www.springframework.org/schema/beans ??
- ????????????http: //www.springframework.org/schema/beans/spring-beans-2.0.xsd ??
- ????????????http: //www.springframework.org/schema/aop ??
- ????????????http: //www.springframework.org/schema/aop/spring-aop-2.5.xsd" ??
- ???? default -autowire= "autodetect" >??
- ????<aop:config>??
- ????????<aop:aspect?id= "TestAspect" ?ref= "aspectBean" >??
- ????????????<!--配置com.spring.service包下所有類(lèi)或接口的所有方法-->??
- ????????????<aop:pointcut?id= "businessService" ??
- ????????????????expression= "execution(*?com.spring.service.*.*(..))" ?/>??
- ????????????<aop:before?pointcut-ref= "businessService" ?method= "doBefore" />??
- ????????????<aop:after?pointcut-ref= "businessService" ?method= "doAfter" />??
- ????????????<aop:around?pointcut-ref= "businessService" ?method= "doAround" />??
- ????????????<aop:after-throwing?pointcut-ref= "businessService" ?method= "doThrowing" ?throwing= "ex" />??
- ????????</aop:aspect>??
- ????</aop:config>??
- ??????
- ????<bean?id= "aspectBean" ? class = "com.spring.aop.TestAspect" ?/>??
- ????<bean?id= "aService" ? class = "com.spring.service.AServiceImpl" ></bean>??
- ????<bean?id= "bService" ? class = "com.spring.service.BServiceImpl" ></bean>??
- ??
- </beans>??
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" default-autowire="autodetect"> <aop:config> <aop:aspect id="TestAspect" ref="aspectBean"> <!--配置com.spring.service包下所有類(lèi)或接口的所有方法--> <aop:pointcut id="businessService" expression="execution(* com.spring.service.*.*(..))" /> <aop:before pointcut-ref="businessService" method="doBefore"/> <aop:after pointcut-ref="businessService" method="doAfter"/> <aop:around pointcut-ref="businessService" method="doAround"/> <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/> </aop:aspect> </aop:config> <bean id="aspectBean" class="com.spring.aop.TestAspect" /> <bean id="aService" class="com.spring.service.AServiceImpl"></bean> <bean id="bService" class="com.spring.service.BServiceImpl"></bean> </beans>
?
??? 測(cè)試類(lèi)AOPTest
- public ? class ?AOPTest? extends ?AbstractDependencyInjectionSpringContextTests?{??
- ??????
- ???? private ?AService?aService;??
- ??????
- ???? private ?BServiceImpl?bService;??
- ??????
- ???? protected ?String[]?getConfigLocations()?{??
- ????????String[]?configs?=? new ?String[]?{? "/applicationContext.xml" };??
- ???????? return ?configs;??
- ????}??
- ??????
- ??????
- ???? /** ?
- ?????*?測(cè)試正常調(diào)用 ?
- ?????*/ ??
- ???? public ? void ?testCall()??
- ????{??
- ????????System.out.println( "SpringTest?JUnit?test" );??
- ????????aService.fooA( "JUnit?test?fooA" );??
- ????????aService.barA();??
- ????????bService.fooB();??
- ????????bService.barB( "JUnit?test?barB" , 0 );??
- ????}??
- ??????
- ???? /** ?
- ?????*?測(cè)試After-Throwing ?
- ?????*/ ??
- ???? public ? void ?testThrow()??
- ????{??
- ???????? try ?{??
- ????????????bService.barB( "JUnit?call?barB" , 1 );??
- ????????}? catch ?(IllegalArgumentException?e)?{??
- ??????????????
- ????????}??
- ????}??
- ??????
- ???? public ? void ?setAService(AService?service)?{??
- ????????aService?=?service;??
- ????}??
- ??????
- ???? public ? void ?setBService(BServiceImpl?service)?{??
- ????????bService?=?service;??
- ????}??
- }??
public class AOPTest extends AbstractDependencyInjectionSpringContextTests { private AService aService; private BServiceImpl bService; protected String[] getConfigLocations() { String[] configs = new String[] { "/applicationContext.xml"}; return configs; } /** * 測(cè)試正常調(diào)用 */ public void testCall() { System.out.println("SpringTest JUnit test"); aService.fooA("JUnit test fooA"); aService.barA(); bService.fooB(); bService.barB("JUnit test barB",0); } /** * 測(cè)試After-Throwing */ public void testThrow() { try { bService.barB("JUnit call barB",1); } catch (IllegalArgumentException e) { } } public void setAService(AService service) { aService = service; } public void setBService(BServiceImpl service) { bService = service; } }
?
??? 運(yùn)行結(jié)果如下:
- log?Begining?method:?com.spring.service.AServiceImpl.fooA??
- AServiceImpl.fooA(msg:JUnit?test?fooA)??
- log?Ending?method:?com.spring.service.AServiceImpl.fooA??
- process?time:? 0 ?ms??
- log?Begining?method:?com.spring.service.AServiceImpl.barA??
- AServiceImpl.barA()??
- log?Ending?method:?com.spring.service.AServiceImpl.barA??
- process?time:? 0 ?ms??
- log?Begining?method:?com.spring.service.BServiceImpl.fooB??
- BServiceImpl.fooB()??
- log?Ending?method:?com.spring.service.BServiceImpl.fooB??
- process?time:? 0 ?ms??
- log?Begining?method:?com.spring.service.BServiceImpl.barB??
- BServiceImpl.barB(msg:JUnit?test?barB?type: 0 )??
- log?Ending?method:?com.spring.service.BServiceImpl.barB??
- process?time:? 0 ?ms??
- ??
- log?Begining?method:?com.spring.service.BServiceImpl.barB??
- BServiceImpl.barB(msg:JUnit?call?barB?type: 1 )??
- log?Ending?method:?com.spring.service.BServiceImpl.barB??
- method?com.spring.service.BServiceImpl.barB? throw ?exception??
- 測(cè)試異常??
log Begining method: com.spring.service.AServiceImpl.fooA AServiceImpl.fooA(msg:JUnit test fooA) log Ending method: com.spring.service.AServiceImpl.fooA process time: 0 ms log Begining method: com.spring.service.AServiceImpl.barA AServiceImpl.barA() log Ending method: com.spring.service.AServiceImpl.barA process time: 0 ms log Begining method: com.spring.service.BServiceImpl.fooB BServiceImpl.fooB() log Ending method: com.spring.service.BServiceImpl.fooB process time: 0 ms log Begining method: com.spring.service.BServiceImpl.barB BServiceImpl.barB(msg:JUnit test barB type:0) log Ending method: com.spring.service.BServiceImpl.barB process time: 0 ms log Begining method: com.spring.service.BServiceImpl.barB BServiceImpl.barB(msg:JUnit call barB type:1) log Ending method: com.spring.service.BServiceImpl.barB method com.spring.service.BServiceImpl.barB throw exception 測(cè)試異常
?
??? 《Spring參考手冊(cè)》中定義了以下幾個(gè)AOP的重要概念,結(jié)合以上代碼分析如下:
- 切面(Aspect) :官方的抽象定義為“一個(gè)關(guān)注點(diǎn)的模塊化,這個(gè)關(guān)注點(diǎn)可能會(huì)橫切多個(gè)對(duì)象”,在本例中,“切面”就是類(lèi)TestAspect所關(guān)注的具體行為,例如,AServiceImpl.barA()的調(diào)用就是切面TestAspect所關(guān)注的行為之一。“切面”在ApplicationContext中<aop:aspect>來(lái)配置。
- 連接點(diǎn)(Joinpoint) :程序執(zhí)行過(guò)程中的某一行為,例如,AServiceImpl.barA()的調(diào)用或者BServiceImpl.barB(String _msg, int _type)拋出異常等行為。
- 通知(Advice) :“切面”對(duì)于某個(gè)“連接點(diǎn)”所產(chǎn)生的動(dòng)作,例如,TestAspect中對(duì)com.spring.service包下所有類(lèi)的方法進(jìn)行日志記錄的動(dòng)作就是一個(gè)Advice。其中,一個(gè)“切面”可以包含多個(gè)“Advice”,例如TestAspect
- 切入點(diǎn)(Pointcut) :匹配連接點(diǎn)的斷言,在AOP中通知和一個(gè)切入點(diǎn)表達(dá)式關(guān)聯(lián)。例如,TestAspect中的所有通知所關(guān)注的連接點(diǎn),都由切入點(diǎn)表達(dá)式execution(* com.spring.service.*.*(..))來(lái)決定
- 目標(biāo)對(duì)象(Target Object) :被一個(gè)或者多個(gè)切面所通知的對(duì)象。例如,AServcieImpl和BServiceImpl,當(dāng)然在實(shí)際運(yùn)行時(shí),Spring AOP采用代理實(shí)現(xiàn),實(shí)際AOP操作的是TargetObject的代理對(duì)象。
-
AOP代理(AOP Proxy)
在Spring AOP中有兩種代理方式,JDK動(dòng)態(tài)代理和CGLIB代理。默認(rèn)情況下,TargetObject實(shí)現(xiàn)了接口時(shí),則采用JDK動(dòng)態(tài)代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。強(qiáng)制使用CGLIB代理需要將
<aop:config>
的proxy-target-class
屬性設(shè)為true
?????? 通知(Advice)類(lèi)型
- 前置通知(Before advice) :在某連接點(diǎn)(JoinPoint)之前執(zhí)行的通知,但這個(gè)通知不能阻止連接點(diǎn)前的執(zhí)行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素進(jìn)行聲明。例如,TestAspect中的doBefore方法
- 后通知(After advice) :當(dāng)某連接點(diǎn)退出的時(shí)候執(zhí)行的通知(不論是正常返回還是異常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素進(jìn)行聲明。例如,TestAspect中的doAfter方法,所以AOPTest中調(diào)用BServiceImpl.barB拋出異常時(shí),doAfter方法仍然執(zhí)行
- 返回后通知(After return advice) :在某連接點(diǎn)正常完成后執(zhí)行的通知,不包括拋出異常的情況。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素進(jìn)行聲明。
- 環(huán)繞通知(Around advice) :包圍一個(gè)連接點(diǎn)的通知,類(lèi)似Web中Servlet規(guī)范中的Filter的doFilter方法。可以在方法的調(diào)用前后完成自定義的行為,也可以選擇不執(zhí)行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素進(jìn)行聲明。例如,TestAspect中的doAround方法。
- 拋出異常后通知(After throwing advice) : 在方法拋出異常退出時(shí)執(zhí)行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素進(jìn)行聲明。例如,TestAspect中的doThrowing方法。
?????? 切入點(diǎn)表達(dá)式
- 通常情況下,表達(dá)式中使用”execution“就可以滿足大部分的要求。表達(dá)式格式如下:
- execution(modifiers-pattern??ret-type-pattern?declaring-type-pattern??name-pattern(param-pattern)? throws -pattern?)??
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
modifiers-pattern:方法的操作權(quán)限
ret-type-pattern:返回值
declaring-type-pattern:方法所在的包
name-pattern:方法名
parm-pattern:參數(shù)名
throws-pattern:異常
其中,除ret-type-pattern和name-pattern之外,其他都是可選的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值為任意類(lèi)型;方法名任意;參數(shù)不作限制的所有方法。
- 通知參數(shù)
可以通過(guò)args來(lái)綁定參數(shù),這樣就可以在通知(Advice)中訪問(wèn)具體參數(shù)了。例如,<aop:aspect>配置如下
- <aop:config>??
- ????<aop:aspect?id= "TestAspect" ?ref= "aspectBean" >??
- ????????<aop:pointcut?id= "businessService" ??
- ????????????expression= "execution(*?com.spring.service.*.*(String,..))?and?args(msg,..)" ?/>??
- ????????????<aop:after?pointcut-ref= "businessService" ?method= "doAfter" />??
- ????</aop:aspect>??
- </aop:config>??
<aop:config> <aop:aspect id="TestAspect" ref="aspectBean"> <aop:pointcut id="businessService" expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" /> <aop:after pointcut-ref="businessService" method="doAfter"/> </aop:aspect> </aop:config>
TestAspect的doAfter方法中就可以訪問(wèn)msg參數(shù),但這樣以來(lái)AService中的barA()和BServiceImpl中的barB()就不再是連接點(diǎn),因?yàn)閑xecution(* com.spring.service.*.*(String,..))只配置第一個(gè)參數(shù)為String類(lèi)型的方法。其中,doAfter方法定義如下:
- public ? void ?doAfter(JoinPoint?jp,String?msg)??
public void doAfter(JoinPoint jp,String msg)
- ? 訪問(wèn)當(dāng)前的連接點(diǎn)
任何通知(Advice)方法可以將第一個(gè)參數(shù)定義為
org.aspectj.lang.JoinPoint
類(lèi)型。
JoinPoint
接口提供了一系列有用的方法, 比如
getArgs()
(返回方法參數(shù))、
getThis()
(返回代理對(duì)象)、
getTarget()
(返回目標(biāo))、
getSignature()
(返回正在被通知的方法相關(guān)信息)和
toString()
(打印出正在被通知的方法的有用信息。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
