|
我們使用一個(gè)簡(jiǎn)單的例子來(lái)演示一下Spring中的AOP,這是一個(gè)log的例子,實(shí)際上log是一個(gè)對(duì)于AOP來(lái)說(shuō)很不好的例子,這里我們只為說(shuō)明Spring AOP的使用。
一,首先我們來(lái)創(chuàng)建一個(gè)自己的interceptor。這個(gè)類(lèi)必須繼承org.aopalliance.intercept. MethodInterceptor接口。Spring的AOP框架就是參照aopalliance這個(gè)標(biāo)準(zhǔn)實(shí)現(xiàn)的,所以我們的MyInterceptor要繼承這個(gè)標(biāo)準(zhǔn)中的接口。 這個(gè)接口只有一個(gè)要求實(shí)現(xiàn)的方法: public Object invoke(MethodInvocation methodInvocation) throws Throwable; 下面是我們的MyIntercptor:
對(duì)于上面的代碼需要說(shuō)明的是下面兩行代碼: Object result = methodInvocation.proceed(); return result; 整個(gè)程序的流程是這樣的: 1,先是執(zhí)行在Object result = methodInvocation.proceed();前面的代碼; 2,接著執(zhí)行Object result = methodInvocation.proceed();,它把執(zhí)行控制權(quán)交給了interceptor stack(攔截器棧)內(nèi)的下一個(gè)interceptor,如果沒(méi)有了就交給真正的業(yè)務(wù)方法; 3,然后執(zhí)行return result;之前的代碼; 4,最后執(zhí)行return result;,它把控制權(quán)交回它之上的interceptor,如果沒(méi)有了就退出interceptor stack。 二,寫(xiě)出我們的業(yè)務(wù)對(duì)象及其接口 為了方便我們的業(yè)務(wù)接口只有一個(gè)hello方法:
業(yè)務(wù)對(duì)象的代碼如下:
三,接下來(lái),我們來(lái)看看如何使用我們的寫(xiě)的interceptor。 我們把業(yè)務(wù)對(duì)象作為AOP的target: <bean id="businessTarget" class="com.rst.spring.testaop.BusinessInterfaceImpl"/> 接著在bean定義中聲明interceptor: <bean id="myInterceptor" class="com.rst.spring.testaop.MyInterceptor"/> 最后,我們來(lái)聲明真正的業(yè)務(wù)對(duì)象,通過(guò)使用它的接口以及Spring的ProxyFactoryBean:
這里需要說(shuō)明兩點(diǎn): proxyInterfaces:就是我們的業(yè)務(wù)對(duì)象的實(shí)際接口; interceptorNames:定義了所有interceptors的執(zhí)行順序,其中業(yè)務(wù)對(duì)象的target作為list的最后一個(gè)。記著一定要把業(yè)務(wù)對(duì)象的target放到list中,否則你的業(yè)務(wù)對(duì)象就不會(huì)工作。 四,最后,寫(xiě)我們的測(cè)試類(lèi)
一切正常就可以在log上看到相應(yīng)的信息了。 以下是附件源代碼的執(zhí)行效果: 2004-09-08 16:04:51,210 INFO - Beginning method (1): interface com.rst.spring.testaop.BusinessInterface.hello() 2004-09-08 16:04:51,210 INFO - Beginning method (2): interface com.rst.spring.testaop.BusinessInterface.hello() hello Spring AOP. 2004-09-08 16:04:51,210 INFO - Ending method (2): interface com.rst.spring.testaop.BusinessInterface.hello() 2004-09-08 16:04:51,210 INFO - Ending method (1): interface com.rst.spring.testaop.BusinessInterface.hello() 2004-09-08 16:04:51,210 INFO - Method invocation time (1): 0 ms. 源代碼需要spring.jar, aopallience.jar, commons-logging.jar。 Spring AOP是一個(gè)很方便高效的框架,尤其在事務(wù)管理中使用到很多,希望能和大家交流。 |
|
|