Spring AOP詳解

AOP

AOP(Aspect Oriented Programming),即面向切面編程,它利用一種稱為"橫切"的技術(shù),剖解開封裝的對(duì)象內(nèi)部,并將那些影響了多個(gè)類的公共行為封裝到一個(gè)可重用模塊,并將其命名為"Aspect",即切面。所謂"切面",簡(jiǎn)單說就是那些與業(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 aop 將默認(rèn)通過jdk 動(dòng)態(tài)代理來(lái)實(shí)現(xiàn)代理類,當(dāng)需要代理的類是繼承的方式則spring aop 將通過cglib 來(lái)實(shí)現(xiàn)代理類

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)

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

1、aopalliance.jar
2、aspectjweaver.jar
3、asm.jar
4、cglib.jar 。

開始講解用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</pre>

看到給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");
    }
}
<?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</pre>

要想讓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>

表示timeHandler只會(huì)織入HelloWorld接口print開頭的方法,logHandler只會(huì)織入HelloWorld接口do開頭的方法

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

前面說過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è)屬性被省略,那么基于接口的代理將起作用

使用注解方式實(shí)現(xiàn)AOP
/**
 * 業(yè)務(wù)類
 */
@Component
public class Business {
}

b、切面類:

@Aspect : 標(biāo)記為切面類
@Pointcut : 指定匹配切點(diǎn)
@Before : 指定前置通知,value中指定切入點(diǎn)匹配

@AfterReturning :后置通知,具有可以指定返回值
@AfterThrowing :異常通知

/**
 * 定義切面
 */
@Component
@Aspect
public class AspectAdvice {

    /**
     * 指定切入點(diǎn)匹配表達(dá)式,注意它是以方法的形式進(jìn)行聲明的。
     */
    @Pointcut("execution(* aop.annotation.*.*(..))")
    public void anyMethod() {
    }

    /**
     * 前置通知
     */
    @Before(value = "execution(* aop.annotation.*.*(..))")
    public void doBefore() {
        System.out.println("===========進(jìn)入before advice============ \n");
    }

    /**
     * 后置通知
     */
    @AfterReturning(value = "anyMethod()", returning = "result")
    public void doAfter() {
        System.out.println("==========進(jìn)入after advice========");
  
    }

    /**
     * 環(huán)繞通知
     */
    @Around(value = "execution(* aop.annotation.*.*(..))")
    public void doAround() throws Throwable {
        System.out.println("===========進(jìn)入around環(huán)繞方法");

    }

    /**
     * 異常通知
     */
    @AfterThrowing(value = "execution(* aop.annotation.*.*(..))", throwing = "e")
    public void doThrow() {
        System.out.println("=====================");
    }

}

c、配置:

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="     
          http://www.springframework.org/schema/beans     
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
          http://www.springframework.org/schema/context     
          http://www.springframework.org/schema/context/spring-context-3.0.xsd 
          http://www.springframework.org/schema/aop     
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    default-autowire="byName">

    <context:component-scan base-package="aop.annotation" />
    <!-- 打開aop 注解 -->
    <aop:aspect-autoproxy />
</beans>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容