Spring-aop實現切面的四種方式(1)

來源:互聯網
上載者:User

標籤:時機   原理   單一職責   epp   ntc   調用   property   預設   位元組   

Spring實現AOP的4種方式

 

  先瞭解AOP的相關術語:
1.通知(Advice):
通知定義了切面是什麼以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。
2.連接點(Joinpoint):
程式能夠應用通知的一 個“時機”,這些“時機”就是連接點,例如方法被調用時、異常被拋出時等等。
3.切入點(Pointcut)
通知定義了切面要發生的“故事”和時間,那麼切入點就定義了“故事”發生的地點,例如某個類或方法的名稱,spring中允許我們方便的用Regex來指定
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.使用Regex2.使用AspectJ運算式AspectJ我不是很熟悉(我也是熟悉
黨 or 精通黨?),我還是習慣用Regex
Spring使用org.springframework.aop.support.JdkRegexpMethodPointcut來定義Regex切點
<bean id="spleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
  <property name="pattern" value=".*sleep"/>
</bean>
pattern屬性指定了Regex,它匹配所有的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的方式:使用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配置即可:
<aop:config>
    <aop:aspect ref="sleepHelper">
    <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>
    <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>
    </aop:aspect>
</aop:config>

spring對AOP的支援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 

Spring-aop實現切面的四種方式(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.