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的接口, 所有具有睡覺能力的東西都可以實現該接口(不光生物,包括關機選項裏面的休眠)
- package test.spring.aop.bean
- public interface Sleepable{
- void sleep();
- }
然後寫一個Human類,他實現了這個接口
- package test.spring.aop.bean
- public Human implements Sleepable{
- /*這人莫非跟寡人差不多?
- *除了睡覺睡的比較好之外其餘的什麼也不會做?*/
- public void sleep(){
- System.out.println("睡覺了!夢中自有顏如玉!");
- }
- }
好了,這是主角,不過睡覺前後要做些輔助工作的,最基本的是脫穿衣服,失眠的人還要吃安眠藥什麼的,但是這些動作與純粹的睡覺這一“業務邏輯”是不相干的,如果把
這些代碼全部加入到sleep方法中,是不是有違單一職責呢?,這時候我們就需要AOP了。
編寫一個SleepHelper類,它裏面包含了睡覺的輔助工作,用AOP術語來說它就應該是通知了,我們需要實現上面的接口
- package test.spring.aop.bean;
- import java.lang.reflect.Method;
- import org.springframework.aop.AfterReturningAdvice;
- import org.springframework.aop.MethodBeforeAdvice;
- public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{
- public void before(Method mtd, Object[] arg1, Object arg2)
- throws Throwable {
- System.out.println("通常情況下睡覺之前要脫衣服!");
- }
- public void afterReturning(Object arg0, Method arg1, Object[] arg2,
- Object arg3) throws Throwable {
- System.out.println("起牀後要先穿衣服!");
- }
- }
然後在spring配置文件中進行配置:
- <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">
- </bean>
OK!現在創建通知的工作就完成了.
第二步是進行配置,這是很令人蛋疼的操作,尤其是這麼熱的天,Spring又把東西的名字起的見鬼的長!它爲啥不能像usr這種風格呢?
首先要做的是配置一個切點,據說切點的表示方式在Spring中有好幾種,但是常用的只有兩種:
Spring使用org.springframework.aop.support.JdkRegexpMethodPointcut來定義正則表達式切點
- <bean id="spleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
- <property name="pattern" value=".*sleep"/>
- </bean>
pattern屬性指定了正則表達式,它匹配所有的sleep方法
切點僅僅是定義了故事發生的地點,還有故事發生的時間以及最重要的故事的內容,就是通知了,我們需要把通知跟切點結合起來,我們要使用的通知者是:
- org.springframework.aop.support.DefaultPointcutAdvisor
- <bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
- <property name="advice" ref="sleepHelper"/>
- <property name="pointcut" ref="sleepPointcut"/>
- </bean>
切入點和通知都配置完成,接下來該調用ProxyFactoryBean產生代理對象了
- <bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
- <property name="target" ref="human"/>
- <property name="interceptorNames" value="sleepHelperAdvisor" />
- <property name="proxyInterfaces" value="test.spring.aop.bean.Sleepable" />
- </bean>
ProxyFactoryBean是一個代理,我們可以把它轉換爲proxyInterfaces中指定的實現該interface的代理對象:
- import org.springframework.aop.framework.ProxyFactoryBean;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import test.spring.aop.bean.Sleepable;
- public class Test {
- public static void main(String[] args){
- ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
- Sleepable sleeper = (Sleepable)appCtx.getBean("humanProxy");
- sleeper.sleep();
- }
- }
程序運行產生結果:
通常情況下睡覺之前要脫衣服!
睡覺啦~夢中自有顏如玉!
起牀後要先穿衣服!
OK! 這是我們想要的結果,但是上面這個過程貌似有點複雜,尤其是配置切點跟通知, Spring提供了一種自動代理的功能,能讓切點跟通知自動進行匹配,修改配置文件如下:
- <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">
- </bean>
- <bean id="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
- <property name="advice" ref="sleepHelper"/>
- <property name="pattern" value=".*sleep"/>
- </bean>
- <bean id="human" class="test.spring.aop.bean.Human">
- </bean>
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
執行程序:
- public class Test {
- public static void main(String[] args){
- ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
- Sleepable sleeper = (Sleepable)appCtx.getBean("human");
- sleeper.sleep();
- }
- }
成功輸出結果跟前面一樣!
只要我們聲明瞭org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator(我勒個去的,名太長了)就能爲方法匹配的bean自動創建代理!
但是這樣還是要有很多工作要做,有更簡單的方式嗎?有!
一種方式是使用AspectJ提供的註解:
- package test.mine.spring.bean;
- import org.aspectj.lang.annotation.AfterReturning;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- @Aspect
- public class SleepHelper {
- public SleepHelper(){
- }
- @Pointcut("execution(* *.sleep())")
- public void sleeppoint(){}
- @Before("sleeppoint()")
- public void beforeSleep(){
- System.out.println("睡覺前要脫衣服!");
- }
- @AfterReturning("sleeppoint()")
- public void afterSleep(){
- System.out.println("睡醒了要穿衣服!");
- }
- }
用@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標註的切面了
最後是運行,很簡單方便了:
- public class Test {
- public static void main(String[] args){
- ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
- Sleepable human = (Sleepable)appCtx.getBean("human");
- human.sleep();
- }
- }
前面我們用到了<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配置即可:
- <aop:config>
- <aop:aspect ref="sleepHelper">
- <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>
- <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>
- </aop:aspect>
- </aop:config>