10 Spring AOP

AOP(Aspect Oriented Programming壮不,面向切面編程)补箍,通過(guò)提供另一種思考程序的方式來(lái)補(bǔ)充OOP(Object Oriented Programming替裆,面向?qū)ο缶幊蹋┐朴纭OP是橫向抽取,OOP是縱向抽象臼婆。
切面可以用于事務(wù)管理抒痒、日志等方面的模塊化

AOP核心概念

  • Aspect(切面)
  • Join Point(連接點(diǎn))
  • Advice(通知/增強(qiáng))
  • Pointcut(切點(diǎn))
  • Introduction(引入)
  • Target Object(目標(biāo)對(duì)象)
  • AOP Proxy(AOP代理)
  • Weaving(織入)

其中,Advice的主要類(lèi)型有:

  • Before Advice(前置通知)
  • After Returning Advice(返回后通知)
  • After Throwing Advice(拋出異常后通知)
  • After (finally)Advice(最后通知)
  • Around Advice(環(huán)繞通知)

切入點(diǎn)和連接點(diǎn)的匹配颁褂,是AOP的關(guān)鍵

Spring AOP

Spring AOP用純Java實(shí)現(xiàn)故响,目前僅支持方法調(diào)用作為連接點(diǎn)。
Spring AOP通常和Spring IoC容器一起使用

Hello的前置增強(qiáng)練習(xí)

  • pom.xml中添加AOP相關(guān)依賴
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring</groupId>
    <artifactId>aop</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>aop</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.1.5.RELEASE</spring.version>
        <aspectj.version>1.9.2</aspectj.version>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <slf4j.version>1.7.12</slf4j.version>
    </properties>

    <dependencies>
        <!--spring-context依賴-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--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>
        <!--spring-test依賴-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--junit依賴-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- log4j日志依賴 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.7.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
  • Hello接口和實(shí)現(xiàn)類(lèi)
package com.spring.aop;

public interface Hello {
    String sayHello();
}
package com.spring.aop;

public class HelloImpl implements Hello {
    @Override
    public String sayHello() {
        return "Spring AOP";
    }
}
  • MyBefore類(lèi)
package com.spring.aop;

/**
 * 用戶自定義前置增強(qiáng)類(lèi)
 */
public class MyBefore {
    public void beforeMethod() {
        System.out.println("This is a before method...");
    }
 }
  • 配置文件
    <bean id="hello" class="com.spring.aop.HelloImpl"/>
    <bean id="myBefore" class="com.spring.aop.MyBefore"/>
    <aop:config>
        <aop:aspect id="before" ref="myBefore">
            <aop:pointcut id="myPointcut" expression="execution(* com.spring.aop.*.*(..))"/>
            <aop:before method="beforeMethod" pointcut-ref="myPointcut"/>
        </aop:aspect>
    </aop:config>
  • 應(yīng)用主類(lèi)
package com.spring.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        Hello hello = (Hello) ac.getBean("hello");
        System.out.println(hello.sayHello());
    }
}
  • 運(yùn)行結(jié)果


    運(yùn)行結(jié)果

可以看到:Mybefore的方法被織入到了Hello的調(diào)用方法前面颁独,前置增強(qiáng)生效

實(shí)戰(zhàn):使用@AspectJ注解的例子

“武松打虎”——武松(Fighter)在山里等著老虎(Tiger)出現(xiàn)彩届,只要發(fā)現(xiàn)老虎出來(lái),就打老虎誓酒。

  • 定義業(yè)務(wù)模型
    Tiger類(lèi)
package com.spring.aspectj;

public class Tiger {
    public void walk() {
        System.out.println("Tiger is walking...");
    }
}
  • 定義切面和配置
    前置通知和后置通知
    Fighter類(lèi)
package com.spring.aspectj;

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 Fighter {
    @Pointcut("execution(* com.spring.aspectj.Tiger.walk())")
    public void foundTiger() {

    }

    @Before(value = "foundTiger()")
    public void foundBefore() {
        System.out.println("Fighter wait for tiger...");
    }

    @AfterReturning("foundTiger()")
    public void foundAfter() {
        System.out.println("Fighter fight with tiger...");
    }
}
  • 配置文件
    <!--啟動(dòng)AspectJ支持-->
    <aop:aspectj-autoproxy/>
    <!--配置bean-->
    <bean id="tiger" class="com.spring.aspectj.Tiger"/>
    <bean id="fighter" class="com.spring.aspectj.Fighter"/>
  • 主程序
package com.spring.aspectj;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FighterApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Tiger tiger = context.getBean(Tiger.class);
        tiger.walk();
    }
}
  • 運(yùn)行結(jié)果


    運(yùn)行結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末樟蠕,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子靠柑,更是在濱河造成了極大的恐慌寨辩,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件歼冰,死亡現(xiàn)場(chǎng)離奇詭異靡狞,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)隔嫡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)甸怕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人腮恩,你說(shuō)我怎么就攤上這事梢杭。” “怎么了秸滴?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵式曲,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)吝羞,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任内颗,我火速辦了婚禮钧排,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘均澳。我一直安慰自己恨溜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布找前。 她就那樣靜靜地躺著糟袁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪躺盛。 梳的紋絲不亂的頭發(fā)上项戴,一...
    開(kāi)封第一講書(shū)人閱讀 51,521評(píng)論 1 304
  • 那天,我揣著相機(jī)與錄音槽惫,去河邊找鬼周叮。 笑死,一個(gè)胖子當(dāng)著我的面吹牛界斜,可吹牛的內(nèi)容都是我干的仿耽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼各薇,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼项贺!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起峭判,我...
    開(kāi)封第一講書(shū)人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤开缎,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后朝抖,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體啥箭,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年治宣,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了急侥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡侮邀,死狀恐怖坏怪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情绊茧,我是刑警寧澤铝宵,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響鹏秋,放射性物質(zhì)發(fā)生泄漏尊蚁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一侣夷、第九天 我趴在偏房一處隱蔽的房頂上張望横朋。 院中可真熱鬧,春花似錦百拓、人聲如沸琴锭。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)决帖。三九已至,卻和暖如春蓖捶,著一層夾襖步出監(jiān)牢的瞬間地回,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工腺阳, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留落君,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓亭引,卻偏偏與公主長(zhǎng)得像绎速,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子焙蚓,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

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