Spring AOP 常用的四種實現方式

Spring實現AOP的四種方式 


先了解AOP的相關術語: 
1.通知(Advice): 
通知定義了切面是什麼以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。
 
2.連接點(Joinpoint): 
程序能夠應用通知的一個“時機”,這些“時機”就是連接點,例如方法被調用時、異常被拋出時等等。 

3.切入點(Pointcut) 
通知定義了切面要發生的“故事”和時間,那麼切入點就定義了“故事”發生的地點,例如某個類或方法的名稱,Spring中允許我們方便的用正則表達式來指定 

4.切面(Aspect) 
通知和切入點共同組成了切面:時間、地點和要發生的“故事” 

5.引入(Introduction) 
引入允許我們向現有的類添加新的方法和屬性(Spring提供了一個方法注入的功能) 

6.目標(Target) 
即被通知的對象,如果沒有AOP,那麼它的邏輯將要交叉別的事務邏輯,有了AOP之後它可以只關注自己要做的事(AOP讓他做愛做的事) 

7.代理(proxy) 
應用通知的對象,詳細內容參見設計模式裏面的代理模式 

8.織入(Weaving) 
把切面應用到目標對象來創建新的代理對象的過程,織入一般發生在如下幾個時機: 
(1)編譯時:當一個類文件被編譯時進行織入,這需要特殊的編譯器纔可以做的到,例如AspectJ的織入編譯器 
(2)類加載時:使用特殊的ClassLoader在目標類被加載到程序之前增強類的字節代碼 
(3)運行時:切面在運行的某個時刻被織入,SpringAOP就是以這種方式織入切面的,原理應該是使用了JDK的動態代理技術 


Spring提供了4種實現AOP的方式: 
1. 經典的基於代理的AOP 
2. @AspectJ註解驅動的切面 
3. 純POJO切面 
4. 注入式AspectJ切面 

首先看, 經典的基於代理的AOP: 


Spring支持五種類型的通知: 
Before(前)  org.apringframework.aop.MethodBeforeAdvice 
After-returning(返回後) org.springframework.aop.AfterReturningAdvice 
After-throwing(拋出後) org.springframework.aop.ThrowsAdvice 
Arround(周圍) org.aopaliance.intercept.MethodInterceptor 
Introduction(引入) org.springframework.aop.IntroductionInterceptor 

值的說明的是周圍通知,他是由AOP Alliance中的接口定義的而非Spring,  周圍通知相當於前通知、返回後通知、拋出後通知的結合

這麼幾個步驟: 
1.創建通知:實現這幾個接口,把其中的方法實現了 
2.定義切點和通知者:在Spring配製文件中配置這些信息 
3.使用ProxyFactoryBean來生成代理 


具體做法。。。大晚上的就舉個睡覺的例子吧: 

首先寫一個接口叫Sleepable,這是一個牛X的接口, 所有具有睡覺能力的東西都可以實現該接口(不光生物,包括關機選項裏面的休眠) 

Java代碼  收藏代碼
  1. package test.spring.aop.bean  
  2.   
  3. public interface Sleepable{  
  4.    
  5.     void sleep();   
  6. }  


然後寫一個Human類,他實現了這個接口 
Java代碼  收藏代碼
  1. package test.spring.aop.bean  
  2.   
  3. public Human implements Sleepable{  
  4.      
  5.    /*這人莫非跟寡人差不多? 
  6.     *除了睡覺睡的比較好之外其餘的什麼也不會做?*/  
  7.    public void sleep(){  
  8.       System.out.println("睡覺了!夢中自有顏如玉!");  
  9.    }  
  10.   
  11. }  


好了,這是主角,不過睡覺前後要做些輔助工作的,最基本的是脫穿衣服,失眠的人還要吃安眠藥什麼的,但是這些動作與純粹的睡覺這一“業務邏輯”是不相干的,如果把 

這些代碼全部加入到sleep方法中,是不是有違單一職責呢?,這時候我們就需要AOP了。 

編寫一個SleepHelper類,它裏面包含了睡覺的輔助工作,用AOP術語來說它就應該是通知了,我們需要實現上面的接口 
Java代碼  收藏代碼
  1. package test.spring.aop.bean;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import org.springframework.aop.AfterReturningAdvice;  
  6. import org.springframework.aop.MethodBeforeAdvice;  
  7.   
  8. public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{  
  9.   
  10.     public void before(Method mtd, Object[] arg1, Object arg2)  
  11.             throws Throwable {  
  12.         System.out.println("通常情況下睡覺之前要脫衣服!");  
  13.     }  
  14.   
  15.     public void afterReturning(Object arg0, Method arg1, Object[] arg2,  
  16.             Object arg3) throws Throwable {  
  17.         System.out.println("起牀後要先穿衣服!");  
  18.     }  
  19.       
  20. }  

然後在spring配置文件中進行配置: 
Xml代碼  收藏代碼
  1. <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">  
  2. </bean>  

OK!現在創建通知的工作就完成了. 


第二步是進行配置,這是很令人蛋疼的操作,尤其是這麼熱的天,Spring又把東西的名字起的見鬼的長!它爲啥不能像usr這種風格呢? 

首先要做的是配置一個切點,據說切點的表示方式在Spring中有好幾種,但是常用的只有兩種:
1.使用正則表達式 2.使用AspectJ表達式 
AspectJ我不是很熟悉(我也是熟悉黨 or 精通黨?), 我還是習慣用正則表達式 

Spring使用org.springframework.aop.support.JdkRegexpMethodPointcut來定義正則表達式切點 
Xml代碼  收藏代碼
  1. <bean id="spleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">  
  2.   <property name="pattern" value=".*sleep"/>  
  3. </bean>  

pattern屬性指定了正則表達式,它匹配所有的sleep方法 

切點僅僅是定義了故事發生的地點,還有故事發生的時間以及最重要的故事的內容,就是通知了,我們需要把通知跟切點結合起來,我們要使用的通知者是: 
Java代碼  收藏代碼
  1. org.springframework.aop.support.DefaultPointcutAdvisor  
  2.   
  3. <bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">  
  4.      <property name="advice" ref="sleepHelper"/>  
  5.      <property name="pointcut" ref="sleepPointcut"/>  
  6. </bean>  

切入點和通知都配置完成,接下來該調用ProxyFactoryBean產生代理對象了 
Xml代碼  收藏代碼
  1. <bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
  2.      <property name="target" ref="human"/>  
  3.      <property name="interceptorNames" value="sleepHelperAdvisor" />  
  4.      <property name="proxyInterfaces" value="test.spring.aop.bean.Sleepable" />  
  5. </bean>  

ProxyFactoryBean是一個代理,我們可以把它轉換爲proxyInterfaces中指定的實現該interface的代理對象: 
Java代碼  收藏代碼
  1. import org.springframework.aop.framework.ProxyFactoryBean;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5. import test.spring.aop.bean.Sleepable;  
  6.   
  7.   
  8. public class Test {  
  9.   
  10.     public static void main(String[] args){  
  11.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  12.         Sleepable sleeper = (Sleepable)appCtx.getBean("humanProxy");  
  13.         sleeper.sleep();  
  14.     }  
  15. }  

程序運行產生結果: 
通常情況下睡覺之前要脫衣服! 
睡覺啦~夢中自有顏如玉! 
起牀後要先穿衣服! 

OK! 這是我們想要的結果,但是上面這個過程貌似有點複雜,尤其是配置切點跟通知, Spring提供了一種自動代理的功能,能讓切點跟通知自動進行匹配,修改配置文件如下: 
Xml代碼  收藏代碼
  1. <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">  
  2.  </bean>  
  3.  <bean id="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  
  4.    <property name="advice" ref="sleepHelper"/>  
  5.    <property name="pattern" value=".*sleep"/>  
  6.  </bean>  
  7.  <bean id="human" class="test.spring.aop.bean.Human">  
  8.  </bean>  
  9.  <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>  

執行程序: 
Java代碼  收藏代碼
  1. public class Test {  
  2.   
  3.     public static void main(String[] args){  
  4.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  5.         Sleepable sleeper = (Sleepable)appCtx.getBean("human");  
  6.         sleeper.sleep();  
  7.     }  
  8. }  

成功輸出結果跟前面一樣! 
只要我們聲明瞭org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator(我勒個去的,名太長了)就能爲方法匹配的bean自動創建代理! 

但是這樣還是要有很多工作要做,有更簡單的方式嗎?有! 


一種方式是使用AspectJ提供的註解: 
Java代碼  收藏代碼
  1. package test.mine.spring.bean;  
  2.   
  3. import org.aspectj.lang.annotation.AfterReturning;  
  4. import org.aspectj.lang.annotation.Aspect;  
  5. import org.aspectj.lang.annotation.Before;  
  6. import org.aspectj.lang.annotation.Pointcut;  
  7. @Aspect  
  8. public class SleepHelper {  
  9.   
  10.     public SleepHelper(){  
  11.           
  12.     }  
  13.       
  14.     @Pointcut("execution(* *.sleep())")  
  15.     public void sleeppoint(){}  
  16.       
  17.     @Before("sleeppoint()")  
  18.     public void beforeSleep(){  
  19.         System.out.println("睡覺前要脫衣服!");  
  20.     }  
  21.       
  22.     @AfterReturning("sleeppoint()")  
  23.     public void afterSleep(){  
  24.         System.out.println("睡醒了要穿衣服!");  
  25.     }  
  26.       
  27. }  

用@Aspect的註解來標識切面,注意不要把它漏了, 否則Spring創建代理的時候會找不到它, @Pointcut註解指定了切點,@Before和@AfterReturning指定了運行時的通知,注意的是要在註解中傳入切點的名稱 

然後我們在Spring配置文件上下點功夫,首先是增加AOP的XML命名空間和聲明相關schema 
命名空間: 
xmlns:aop="http://www.springframework.org/schema/aop" 
schema聲明: 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 

然後加上這個標籤: 
<aop:aspectj-autoproxy/> 有了這個Spring就能夠自動掃描被@Aspect標註的切面了 

最後是運行,很簡單方便了: 
Java代碼  收藏代碼
  1. public class Test {  
  2.   
  3.     public static void main(String[] args){  
  4.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  5.         Sleepable human = (Sleepable)appCtx.getBean("human");  
  6.         human.sleep();  
  7.     }  
  8. }  



下面我們來看最後一種常用的實現AOP的方式:
使用Spring來定義純粹的POJO切面 

前面我們用到了<aop:aspectj-autoproxy/>標籤,Spring在aop的命名空間裏面還提供了其他的配置元素: 
<aop:advisor> 定義一個AOP通知者 
<aop:after> 後通知 
<aop:after-returning> 返回後通知 
<aop:after-throwing> 拋出後通知 
<aop:around> 周圍通知 
<aop:aspect>定義一個切面 
<aop:before>前通知 
<aop:config>頂級配置元素,類似於<beans>這種東西 
<aop:pointcut>定義一個切點 

我們用AOP標籤來實現睡覺這個過程: 
代碼不變,只是修改配置文件,加入AOP配置即可: 
Xml代碼  收藏代碼
  1. <aop:config>  
  2.     <aop:aspect ref="sleepHelper">  
  3.     <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>  
  4.     <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>  
  5.     </aop:aspect>  
  6. </aop:config>  
發佈了0 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章