Spring AOP 面向切面編程詳解

AOP

AOP(Aspect Oriented Programming)尼斧,即面向切面編程,可以說(shuō)是OOP(Object Oriented Programming试吁,面向?qū)ο缶幊蹋┑难a(bǔ)充和完善棺棵。OOP引入封裝、繼承、多態(tài)等概念來(lái)建立一種對(duì)象層次結(jié)構(gòu)烛恤,用于模擬公共行為的一個(gè)集合母怜。不過OOP允許開發(fā)者定義縱向的關(guān)系,但并不適合定義橫向的關(guān)系缚柏,例如日志功能苹熏。日志代碼往往橫向地散布在所有對(duì)象層次中,而與它對(duì)應(yīng)的對(duì)象的核心功能毫無(wú)關(guān)系對(duì)于其他類型的代碼币喧,如安全性柜裸、異常處理和透明的持續(xù)性也都是如此,這種散布在各處的無(wú)關(guān)的代碼被稱為橫切(cross cutting)粱锐,在OOP設(shè)計(jì)中疙挺,它導(dǎo)致了大量代碼的重復(fù),而不利于各個(gè)模塊的重用怜浅。

AOP技術(shù)恰恰相反铐然,它利用一種稱為"橫切"的技術(shù),剖解開封裝的對(duì)象內(nèi)部恶座,并將那些影響了多個(gè)類的公共行為封裝到一個(gè)可重用模塊搀暑,并將其命名為"Aspect",即切面跨琳。所謂"切面"自点,簡(jiǎn)單說(shuō)就是那些與業(yè)務(wù)無(wú)關(guān),卻為業(yè)務(wù)模塊所共同調(diào)用的邏輯或責(zé)任封裝起來(lái)脉让,便于減少系統(tǒng)的重復(fù)代碼桂敛,降低模塊之間的耦合度,并有利于未來(lái)的可操作性和可維護(hù)性溅潜。

使用"橫切"技術(shù)术唬,AOP把軟件系統(tǒng)分為兩個(gè)部分:核心關(guān)注點(diǎn)橫切關(guān)注點(diǎn)。業(yè)務(wù)處理的主要流程是核心關(guān)注點(diǎn)滚澜,與之關(guān)系不大的部分是橫切關(guān)注點(diǎn)粗仓。橫切關(guān)注點(diǎn)的一個(gè)特點(diǎn)是,他們經(jīng)常發(fā)生在核心關(guān)注點(diǎn)的多處设捐,而各處基本相似借浊,比如權(quán)限認(rèn)證、日志萝招、事物蚂斤。AOP的作用在于分離系統(tǒng)中的各種關(guān)注點(diǎn),將核心關(guān)注點(diǎn)和橫切關(guān)注點(diǎn)分離開來(lái)即寒。

AOP核心概念

1橡淆、橫切關(guān)注點(diǎn)

對(duì)哪些方法進(jìn)行攔截,攔截后怎么處理母赵,這些關(guān)注點(diǎn)稱之為橫切關(guān)注點(diǎn)

2逸爵、切面(aspect)

類是對(duì)物體特征的抽象,切面就是對(duì)橫切關(guān)注點(diǎn)的抽象

3凹嘲、連接點(diǎn)(joinpoint)

被攔截到的點(diǎn),因?yàn)镾pring只支持方法類型的連接點(diǎn),所以在Spring中連接點(diǎn)指的就是被攔截到的方法悴晰,實(shí)際上連接點(diǎn)還可以是字段或者構(gòu)造器

4娇澎、切入點(diǎn)(pointcut)

對(duì)連接點(diǎn)進(jìn)行攔截的定義

5、通知(advice)

所謂通知指的就是指攔截到連接點(diǎn)之后要執(zhí)行的代碼凶朗,通知分為前置瓷胧、后置、異常棚愤、最終搓萧、環(huán)繞通知五類

6、目標(biāo)對(duì)象

代理的目標(biāo)對(duì)象

7宛畦、織入(weave)

將切面應(yīng)用到目標(biāo)對(duì)象并導(dǎo)致代理對(duì)象創(chuàng)建的過程

8瘸洛、引入(introduction)

在不修改代碼的前提下,引入可以在運(yùn)行期為類動(dòng)態(tài)地添加一些方法或字段

Spring對(duì)AOP的支持

Spring中AOP代理由Spring的IOC容器負(fù)責(zé)生成次和、管理反肋,其依賴關(guān)系也由IOC容器負(fù)責(zé)管理。因此踏施,AOP代理可以直接使用容器中的其它bean實(shí)例作為目標(biāo)石蔗,這種關(guān)系可由IOC容器的依賴注入提供。Spring創(chuàng)建代理的規(guī)則為:

1畅形、默認(rèn)使用Java動(dòng)態(tài)代理來(lái)創(chuàng)建AOP代理抓督,這樣就可以為任何接口實(shí)例創(chuàng)建代理了

2、當(dāng)需要代理的類不是代理接口的時(shí)候束亏,Spring會(huì)切換為使用CGLIB代理铃在,也可強(qiáng)制使用CGLIB

AOP編程其實(shí)是很簡(jiǎn)單的事情,縱觀AOP編程碍遍,程序員只需要參與三個(gè)部分:

1定铜、定義普通業(yè)務(wù)組件

2、定義切入點(diǎn)怕敬,一個(gè)切入點(diǎn)可能橫切多個(gè)業(yè)務(wù)組件

3揣炕、定義增強(qiáng)處理,增強(qiáng)處理就是在AOP框架為普通業(yè)務(wù)組件織入的處理動(dòng)作

所以進(jìn)行AOP編程的關(guān)鍵就是定義切入點(diǎn)和定義增強(qiáng)處理东跪,一旦定義了合適的切入點(diǎn)和增強(qiáng)處理畸陡,AOP框架將自動(dòng)生成AOP代理鹰溜,即:代理對(duì)象的方法=增強(qiáng)處理+被代理對(duì)象的方法。

下面給出一個(gè)Spring AOP的.xml文件模板丁恭,名字叫做aop.xml曹动,之后的內(nèi)容都在aop.xml上進(jìn)行擴(kuò)展:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
</beans>

基于Spring的AOP簡(jiǎn)單實(shí)現(xiàn)

注意一下,在講解之前牲览,說(shuō)明一點(diǎn):使用Spring AOP墓陈,要成功運(yùn)行起代碼,只用Spring提供給開發(fā)者的jar包是不夠的第献,請(qǐng)額外上網(wǎng)下載兩個(gè)jar包:

1贡必、aopalliance.jar

2、aspectjweaver.jar

如果是maven項(xiàng)目的話就要在pom.xml中加:

1庸毫、spring-aop

2仔拟、spring-aspects

開始講解用Spring AOP的XML實(shí)現(xiàn)方式,先定義一個(gè)接口:

public interface HelloWorld
{
    void printHelloWorld();
    void doPrint();
}

定義兩個(gè)接口實(shí)現(xiàn)類:

public class HelloWorldImpl1 implements HelloWorld
{
    public void printHelloWorld()
    {
        System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
    }
    
    public void doPrint()
    {
        System.out.println("Enter HelloWorldImpl1.doPrint()");
        return ;
    }
}
public class HelloWorldImpl2 implements HelloWorld
{
    public void printHelloWorld()
    {
        System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
    }
    
    public void doPrint()
    {
        System.out.println("Enter HelloWorldImpl2.doPrint()");
        return ;
    }
}

橫切關(guān)注點(diǎn)飒赃,這里是打印時(shí)間:

public class TimeHandler
{
    public void printTime()
    {
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }
}

有這三個(gè)類就可以實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Spring AOP了理逊,看一下aop.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
        
        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
        
        <aop:config>
            <aop:aspect id="time" ref="timeHandler">
                <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
                <aop:before method="printTime" pointcut-ref="addAllMethod" />
                <aop:after method="printTime" pointcut-ref="addAllMethod" />
            </aop:aspect>
        </aop:config>
</beans>

寫一個(gè)main函數(shù)調(diào)用一下:

public static void main(String[] args)
{
    ApplicationContext ctx = 
            new ClassPathXmlApplicationContext("aop.xml");
        
    HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1");
    HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2");
    hw1.printHelloWorld();
    System.out.println();
    hw1.doPrint();
    
    System.out.println();
    hw2.printHelloWorld();
    System.out.println();
    hw2.doPrint();
}
運(yùn)行結(jié)果為:
CurrentTime = 1446129611993
Enter HelloWorldImpl1.printHelloWorld()
CurrentTime = 1446129611993

CurrentTime = 1446129611994
Enter HelloWorldImpl1.doPrint()
CurrentTime = 1446129611994

CurrentTime = 1446129611994
Enter HelloWorldImpl2.printHelloWorld()
CurrentTime = 1446129611994

CurrentTime = 1446129611994
Enter HelloWorldImpl2.doPrint()
CurrentTime = 1446129611994

看到給HelloWorld接口的兩個(gè)實(shí)現(xiàn)類的所有方法都加上了代理,代理內(nèi)容就是打印時(shí)間

基于Spring的AOP使用其他細(xì)節(jié)

1盒揉、增加一個(gè)橫切關(guān)注點(diǎn)晋被,打印日志,Java類為:

public class LogHandler
{
    public void LogBefore()
    {
        System.out.println("Log before method");
    }
    
    public void LogAfter()
    {
        System.out.println("Log after method");
    }
}

aop.xml配置為:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
        
        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
        <bean id="logHandler" class="com.xrq.aop.LogHandler" />
        
        <aop:config>
            <aop:aspect id="time" ref="timeHandler" order="1">
                <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
                <aop:before method="printTime" pointcut-ref="addTime" />
                <aop:after method="printTime" pointcut-ref="addTime" />
            </aop:aspect>
            <aop:aspect id="log" ref="logHandler" order="2">
                <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
                <aop:before method="LogBefore" pointcut-ref="printLog" />
                <aop:after method="LogAfter" pointcut-ref="printLog" />
            </aop:aspect>
        </aop:config>
</beans>

測(cè)試類不變刚盈,打印結(jié)果為:

CurrentTime = 1446130273734
Log before method
Enter HelloWorldImpl1.printHelloWorld()
Log after method
CurrentTime = 1446130273735

CurrentTime = 1446130273736
Log before method
Enter HelloWorldImpl1.doPrint()
Log after method
CurrentTime = 1446130273736

CurrentTime = 1446130273736
Log before method
Enter HelloWorldImpl2.printHelloWorld()
Log after method
CurrentTime = 1446130273736

CurrentTime = 1446130273737
Log before method
Enter HelloWorldImpl2.doPrint()
Log after method
CurrentTime = 1446130273737

要想讓logHandler在timeHandler前使用有兩個(gè)辦法:

(1)aspect里面有一個(gè)order屬性羡洛,order屬性的數(shù)字就是橫切關(guān)注點(diǎn)的順序

(2)把logHandler定義在timeHandler前面,Spring默認(rèn)以aspect的定義順序作為織入順序

2藕漱、我只想織入接口中的某些方法

修改一下pointcut的expression就好了:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
        
        <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
        <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
        <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
        <bean id="logHandler" class="com.xrq.aop.LogHandler" />
        
        <aop:config>
            <aop:aspect id="time" ref="timeHandler" order="1">
                <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.print*(..))" />
                <aop:before method="printTime" pointcut-ref="addTime" />
                <aop:after method="printTime" pointcut-ref="addTime" />
            </aop:aspect>
            <aop:aspect id="log" ref="logHandler" order="2">
                <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.do*(..))" />
                <aop:before method="LogBefore" pointcut-ref="printLog" />
                <aop:after method="LogAfter" pointcut-ref="printLog" />
            </aop:aspect>
        </aop:config>
</beans>

可以看到expression字段欲侮,表示timeHandler只會(huì)織入HelloWorld接口print開頭的方法,logHandler只會(huì)織入HelloWorld接口do開頭的方法.

3肋联、強(qiáng)制使用CGLIB生成代理

前面說(shuō)過Spring使用動(dòng)態(tài)代理或是CGLIB生成代理是有規(guī)則的威蕉,高版本的Spring會(huì)自動(dòng)選擇是使用動(dòng)態(tài)代理還是CGLIB生成代理內(nèi)容,當(dāng)然我們也可以強(qiáng)制使用CGLIB生成代理橄仍,那就是<aop:config>里面有一個(gè)"proxy-target-class"屬性韧涨,這個(gè)屬性值如果被設(shè)置為true,那么基于類的代理將起作用侮繁,如果proxy-target-class被設(shè)置為false或者這個(gè)屬性被省略虑粥,那么基于接口的代理將起作用

原理區(qū)別:

java動(dòng)態(tài)代理是利用反射機(jī)制生成一個(gè)實(shí)現(xiàn)代理接口的匿名類,在調(diào)用具體方法前調(diào)用InvokeHandler來(lái)處理宪哩。而cglib動(dòng)態(tài)代理是利用asm開源包娩贷,對(duì)代理對(duì)象類的class文件加載進(jìn)來(lái),通過修改其字節(jié)碼生成子類來(lái)處理锁孟。

1彬祖、如果目標(biāo)對(duì)象實(shí)現(xiàn)了接口茁瘦,默認(rèn)情況下會(huì)采用JDK的動(dòng)態(tài)代理實(shí)現(xiàn)AOP 
2、如果目標(biāo)對(duì)象實(shí)現(xiàn)了接口储笑,可以強(qiáng)制使用CGLIB實(shí)現(xiàn)AOP 
3甜熔、如果目標(biāo)對(duì)象沒有實(shí)現(xiàn)了接口,必須采用CGLIB庫(kù)南蓬,spring會(huì)自動(dòng)在JDK動(dòng)態(tài)代理和CGLIB之間轉(zhuǎn)換

PS:
原文地址:http://blog.csdn.net/caomiao2006/article/details/51295158

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市哑了,隨后出現(xiàn)的幾起案子赘方,更是在濱河造成了極大的恐慌,老刑警劉巖弱左,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件窄陡,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡拆火,警方通過查閱死者的電腦和手機(jī)跳夭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)们镜,“玉大人币叹,你說(shuō)我怎么就攤上這事∧O粒” “怎么了颈抚?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)嚼鹉。 經(jīng)常有香客問我贩汉,道長(zhǎng),這世上最難降的妖魔是什么锚赤? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任匹舞,我火速辦了婚禮,結(jié)果婚禮上线脚,老公的妹妹穿的比我還像新娘赐稽。我一直安慰自己,他們只是感情好浑侥,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布又憨。 她就那樣靜靜地躺著,像睡著了一般锭吨。 火紅的嫁衣襯著肌膚如雪蠢莺。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天零如,我揣著相機(jī)與錄音躏将,去河邊找鬼锄弱。 笑死,一個(gè)胖子當(dāng)著我的面吹牛祸憋,可吹牛的內(nèi)容都是我干的会宪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼蚯窥,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼掸鹅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起拦赠,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤巍沙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后荷鼠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體句携,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年允乐,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了矮嫉。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡牍疏,死狀恐怖蠢笋,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鳞陨,我是刑警寧澤挺尿,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站炊邦,受9級(jí)特大地震影響编矾,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜馁害,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一窄俏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧碘菜,春花似錦凹蜈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至计雌,卻和暖如春悄晃,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工妈橄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留庶近,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓眷蚓,卻偏偏與公主長(zhǎng)得像鼻种,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子沙热,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容