Spring AOP 的簡(jiǎn)單應(yīng)用

因?yàn)楣ぷ餍枨螅约喝チ私庖幌耡op并做下的記錄,當(dāng)然大部分都是參考他人博客以及官方文檔烦味。

目錄

<a name="關(guān)于 AOP"></a>

關(guān)于 AOP

大家都知道Spring框架有兩大重要特性礁鲁,IOC 控制反轉(zhuǎn) (Inversion of Control封断,IoC) 以及AOP 面向切面編程(Aspect Oriented Program矛缨, AOP)爹脾。今天主要是來一起了解一下AOP帖旨。

其主要作用是箕昭,在不修改源代碼的情況下給某個(gè)或者一組操作添加額外的功能。像日志記錄解阅,事務(wù)處理落竹,權(quán)限控制等功能,都可以用AOP來“優(yōu)雅”地實(shí)現(xiàn)货抄,使這些額外功能和真正的業(yè)務(wù)邏輯分離開來述召,軟件的結(jié)構(gòu)將更加清晰朱转。

簡(jiǎn)單來說在運(yùn)行時(shí),動(dòng)態(tài)地將代碼切入到類的指定方法积暖、指定位置上的編程思想就是面向切面的編程藤为。

<a name = "相關(guān)術(shù)語(yǔ)"></a>

相關(guān)術(shù)語(yǔ)

Aspect(切面)

aspectpointcutadvice組成,它即包含了橫切的定義夺刑,也包含了鏈接點(diǎn)的定義缅疟。由Spring AOP負(fù)責(zé)實(shí)施切面,它將切面所定義的橫切邏輯織入到切面所指定的鏈接點(diǎn)中遍愿。

簡(jiǎn)單來說存淫,只要在類上有 @Aspect 注解的類就是切面。

Join point(鏈接點(diǎn)/記錄點(diǎn))

程序運(yùn)行中的一個(gè)點(diǎn)沼填,例如一個(gè)運(yùn)行方法或者異常處理桅咆。

在Spring AOP中,一個(gè)join point總是一個(gè)運(yùn)行方法坞笙,即只有方法才是連接點(diǎn)岩饼。

advice (增強(qiáng)/通知)

在join point(即滿足 point cut 規(guī)則的join point)上特定的時(shí)刻執(zhí)行的操作,Advice有幾種不同類型薛夜,下文將會(huì)討論(通俗地來講就是起作用的內(nèi)容和時(shí)間點(diǎn))忌愚。

Pointcut(切點(diǎn))

匹配 join point 的謂詞(a predicate that matches join points).

advice 與 pointcut 表達(dá)式相關(guān)聯(lián),并在與 pointcut 匹配的任意 joinpoint 運(yùn)行(例如却邓,執(zhí)行具有特定名稱的方法)硕糊。

簡(jiǎn)單來說 pointcut 是一個(gè)joinpoint 的過濾器,只有滿足 pointcut 的規(guī)則的 joinpoint 才會(huì)執(zhí)行 advice腊徙。

Introduction

為一個(gè)類型添加額外的方法或字段. Spring AOP 允許我們?yōu)?目標(biāo)對(duì)象 引入新的接口(和對(duì)應(yīng)的實(shí)現(xiàn)). 例如我們可以使用 introduction 來為一個(gè) bean 實(shí)現(xiàn) IsModified 接口, 并以此來簡(jiǎn)化 caching 的實(shí)現(xiàn).

Target object

織入一個(gè)或多個(gè) advice 的目標(biāo)對(duì)象. 目標(biāo)對(duì)象也被稱為 advised object.

因?yàn)?Spring AOP 使用運(yùn)行時(shí)代理的方式來實(shí)現(xiàn) aspect, 因此 adviced object 總是一個(gè)代理對(duì)象(proxied object)
注意, adviced object 指的不是原來的類, 而是織入 advice 后所產(chǎn)生的代理類.

AOP proxy

一個(gè)類被 AOP 織入 advice, 就會(huì)產(chǎn)生一個(gè)結(jié)果類, 它是融合了原類和增強(qiáng)邏輯的代理類.在 Spring AOP 中, AOP 代理將是一個(gè) JDK 動(dòng)態(tài)代理對(duì)象或 CGLIB 代理對(duì)象.

Weaving (織入)

將 aspect 和其他對(duì)象連接起來, 并創(chuàng)建 adviced object 的過程.根據(jù)不同的實(shí)現(xiàn)技術(shù), AOP織入有三種方式:

  • 編譯器織入, 這要求有特殊的Java編譯器.
  • 類裝載期織入, 這需要有特殊的類裝載器.
  • 動(dòng)態(tài)代理織入, 在運(yùn)行期為目標(biāo)類添加增強(qiáng)(Advice)生成子類的方式.

與其他純Java AOP框架一樣简十,Spring AOP在運(yùn)行時(shí)執(zhí)行編織。

advice 的類型

  • before advice, 在 join point 前被執(zhí)行的 advice. 雖然 before advice 是在 join point 前被執(zhí)行, 但是它并不能夠阻止 join point 的執(zhí)行, 除非發(fā)生了異常(即我們?cè)?before advice 代碼中, 不能人為地決定是否繼續(xù)執(zhí)行 join point 中的代碼)
  • after return advice, 在一個(gè) join point 正常返回后執(zhí)行的 advice
  • after throwing advice, 當(dāng)一個(gè) join point 拋出異常后執(zhí)行的 advice
  • after(final) advice, 無論一個(gè) join point 是正常退出還是發(fā)生了異常, 都會(huì)被執(zhí)行的 advice.
  • around advice, 在 join point 前和 joint point 退出后都執(zhí)行的 advice. 這個(gè)是最常用的 advice.

Pointcut expression

Pointcut通過pointcut expression來描述撬腾,有若干種限定詞螟蝙。具體可以參考Spring文檔7.2.3 Declaring a pointcutaspectj-cheat-sheet.

<a name="Spring AOP的使用"></a>

Spring AOP的使用

我們可以通過三種方式來使用Spring AOP,他們分別是:@Aspect-based(Annotation)民傻,Schema-based(XML)胰默,以及底層的Spring AOP API。我們后續(xù)講解的主要是基于注解的實(shí)現(xiàn)漓踢。

使用xml的實(shí)現(xiàn)原理與使用注解基本一致牵署,基本上只是把注解包含的配置信息都轉(zhuǎn)移到了xml配置文件中。

至于AOP API則是Spring1.2提供的歷史用法喧半,現(xiàn)在的Sping4也仍然支持奴迅,注解與xml也是基于其上的使用。它是SpringAOP的基礎(chǔ)挺据,有興趣的可以去參考鏈接4查看取具。

<a name="基于注解的使用"></a>

基于注解的使用

添加 @AspectJ 支持

@AspectJ 是一種使用 Java 注解來實(shí)現(xiàn) AOP 的編碼風(fēng)格.
@AspectJ 風(fēng)格的 AOP 是 AspectJ Project 在 AspectJ 5 中引入的, 并且 Spring 也支持@AspectJ 的 AOP 風(fēng)格.

<a name="添加依賴"></a>

添加依賴

 <!-- 5)Spring AOP -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <!-- aspectj依賴開始 -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>${aspectj.version}</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>${aspectj.version}</version>
  </dependency>
  <!-- aspectj依賴結(jié)束 -->

<a name="開啟 @Aspect 注解"></a>

開啟 @Aspect 注解

    在 spring-mvc.xml 中添加一下語(yǔ)句 用于啟用@Aspect注解
    <aop:aspectj-autoproxy/> //jdk 代理
    或
    <aop:aspectj-autoproxy proxy-target-class="true" /> //cglib 代理

    
    并且需要在xml中加上 aop 的 namespace
    <?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" xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
            <!-- bean definitions here -->

    </beans>

jdk 代理 與 CGlib 代理
JDK動(dòng)態(tài)代理只能對(duì)實(shí)現(xiàn)了接口的類生成代理脖隶,而不能針對(duì)類 。
CGLIB是針對(duì)類實(shí)現(xiàn)代理暇检,主要是對(duì)指定的類生成一個(gè)子類产阱,覆蓋其中的 方法 。
因?yàn)槭抢^承块仆,所以該類或方法最好不要聲明成final 心墅,final可以阻止繼承和多態(tài)。

<a name="定義 aspect(切面)"></a>

定義 aspect(切面)

當(dāng)使用注解 @Aspect 標(biāo)注一個(gè) Bean 后, 那么 Spring 框架會(huì)自動(dòng)收集這些 Bean, 并添加到 Spring AOP 中, 例如:

@Aspect
@Component
public class TestAspect {
}

請(qǐng)注意榨乎,@Aspect 不能被 Spring 自動(dòng)識(shí)別并注冊(cè)為 Bean怎燥;為此,您需要添加一個(gè)單獨(dú)的 @Component 注釋

<a name="聲明 pointcut"></a>

聲明 pointcut

pointcut 聲明由兩部分組成:

Pointcut簽名(signature) 包括方法名和相關(guān)參數(shù)

Pointcut表示式(expression) 用來指定哪些方法執(zhí)行是我們感興趣的(即因此可以織入 advice).


pointcut expression
pointcut expression

這個(gè)方法必須無返回值.
這個(gè)方法本身就是 pointcut signature, pointcut 表達(dá)式使用@Pointcut 注解指定.
上圖定義了一個(gè) pointcut蜜暑,它所描述的是:匹配在項(xiàng)目路徑 aspects.trace.demo 下的所有方法的執(zhí)行

<a name="切點(diǎn)標(biāo)志符"></a>

切點(diǎn)標(biāo)志符(designator)

具體使用請(qǐng)參考案例代碼

  • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
  • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
  • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
  • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
  • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
  • bean - limit the matching of join points to a particular named Spring bean, or to a set of named Spring beans (when using wildcards).
  • @target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type
  • @args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)
  • @within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)
  • @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

<a name="聲明 advice"></a>

聲明 advice

advice 是和一個(gè) pointcut 表達(dá)式關(guān)聯(lián)在一起的, 并且會(huì)在匹配的 join point 的方法執(zhí)行的前/后/周圍 運(yùn)行. pointcut 表達(dá)式可以是簡(jiǎn)單的一個(gè) pointcut 名字的引用, 或者是完整的 pointcut 表達(dá)式.

* Before

 Before Advice 由切面中的 @Before 注解聲明

 代表 advice 在 joinpoint 之前執(zhí)行
* After returning

 當(dāng)匹配的方法正常執(zhí)行并返回時(shí)運(yùn)行 After returning Advice铐姚。

 由 @AfterReturning 注解聲明

* After throwing 
 當(dāng)匹配的方法執(zhí)行并拋出異常退出時(shí),運(yùn)行肛捍。
 
 由 @AfterThorwing 注解聲明隐绵。

* After (finally)
 當(dāng)匹配的方法執(zhí)行完成并退出后執(zhí)行。
 
 通過 @After 聲明
 
        try{
            try{
                //@Before
                method.invoke(..);
            }finally{
                //@After
            }
            //@AfterReturning
        }catch(){
            //@AfterThrowing
        }

* Around
 它可以在一個(gè)方法的之前之前和之后添加不同的操作, 并且甚至可以決定何時(shí), 如何, 是否調(diào)用匹配到的方法.
 
 通過 @Around 聲明  

<a name = "代碼地址">

代碼地址

https://github.com/Kcyfrank/SpringMVC-example

<a name = "參考鏈接">

參考鏈接:

  1. 官方文檔 Aspect Oriented Programming with Spring
  2. 徹底征服 Spring AOP 之 理論篇
  3. aspectj-cheat-sheet
    <a name = "參考4">
  4. Spring AOP API介紹
  5. spring-aop-target-vs-this
  6. Spring 之AOP AspectJ切入點(diǎn)語(yǔ)法詳解(最全了拙毫,不需要再去其他地找了)
  7. AOP 那點(diǎn)事兒 & 續(xù)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末依许,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子缀蹄,更是在濱河造成了極大的恐慌峭跳,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件缺前,死亡現(xiàn)場(chǎng)離奇詭異蛀醉,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)衅码,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門拯刁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人逝段,你說我怎么就攤上這事垛玻。” “怎么了奶躯?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵帚桩,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我巫糙,道長(zhǎng)朗儒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任参淹,我火速辦了婚禮醉锄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘浙值。我一直安慰自己恳不,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布开呐。 她就那樣靜靜地躺著烟勋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪筐付。 梳的紋絲不亂的頭發(fā)上卵惦,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音瓦戚,去河邊找鬼沮尿。 笑死,一個(gè)胖子當(dāng)著我的面吹牛较解,可吹牛的內(nèi)容都是我干的畜疾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼印衔,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼啡捶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起奸焙,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瞎暑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后与帆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體金顿,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年鲤桥,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了揍拆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茶凳,死狀恐怖嫂拴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贮喧,我是刑警寧澤筒狠,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站箱沦,受9級(jí)特大地震影響辩恼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一灶伊、第九天 我趴在偏房一處隱蔽的房頂上張望疆前。 院中可真熱鬧,春花似錦聘萨、人聲如沸竹椒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)胸完。三九已至,卻和暖如春翘贮,著一層夾襖步出監(jiān)牢的瞬間赊窥,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工狸页, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锨能,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓肴捉,卻偏偏與公主長(zhǎng)得像腹侣,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子齿穗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

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

  • 基本知識(shí) 其實(shí), 接觸了這么久的 AOP, 我感覺, AOP 給人難以理解的一個(gè)關(guān)鍵點(diǎn)是它的概念比較多, 而且坑爹...
    永順閱讀 8,208評(píng)論 5 114
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,509評(píng)論 0 23
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理傲隶,服務(wù)發(fā)現(xiàn),斷路器窃页,智...
    卡卡羅2017閱讀 134,659評(píng)論 18 139
  • What? As we all know跺株,在進(jìn)行項(xiàng)目構(gòu)建時(shí),追求各模塊高內(nèi)聚脖卖,模塊間低耦合乒省。然而現(xiàn)實(shí)并不總是如此美...
    MasterNeo閱讀 2,076評(píng)論 0 17
  • 幾番冷雨過后春風(fēng)蕩漾不息拂過山崗湖泊聽過無數(shù)故事后在這如水的夜里穿過萬(wàn)水和千山 我遙望北方燈火心上的人可無恙你也知...
    茶石閱讀 353評(píng)論 0 2