1. 程式人生 > >Spring-aop實現切面的四種方式 上篇

Spring-aop實現切面的四種方式 上篇

Spring實現AOP的4種方式

  先了解AOP的相關術語:
1.通知(Advice):
通知定義了切面是什麼以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。

程式能夠應用通知的一 時機,這些時機就是連線點,例如方法被呼叫時、異常被丟擲時等等。
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
[email protected]註解驅動的切面
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中有好幾種,但是常用的只有兩種:1.使用正則表示式2.使用AspectJ表示式AspectJ我不是很熟悉(我也是熟悉
or 精通黨?),我還是習慣用正則表示式

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配置檔案上下點功夫,首先是增加AOPXML名稱空間和宣告相關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的方式:使用Spring來定義純粹的POJO切面
前面我們用到了<aop:aspectj-autoproxy/>標籤,Springaop的名稱空間裡面還提供了其他的配置元素:
<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>

springAOP的支援2:

1、如果目標物件實現了介面,預設情況下會採用JDK的動態代理實現AOP
2、如果目標物件實現了介面,可以強制使用CGLIB實現AOP
3、如果目標物件沒有實現了介面,必須採用CGLIB庫,spring會自動在JDK動態代理和CGLIB之間轉換


在實現介面的情況下,如何強制使用CGLIB實現AOP
 * 新增CGLIB庫,SPRING_HOME/cglib/*.jar
 * spring配置檔案中加入<aop:aspectj-autoproxy proxy-target-class="true"/>
 
JDK動態代理和CGLIB位元組碼生成的區別?
 * JDK動態代理只能對實現了介面的類生成代理,而不能針對類
 * CGLIB是針對類實現代理,主要是對指定的類生成一個子類,覆蓋其中的方法
   因為是繼承,所以該類或方法最好不要宣告成final 

 原始碼下篇