Spring系列(四):Spring AOP詳解和實現方式(xml配置和注解配置)


參考文章:http://www.cnblogs.com/hongwz/p/5764917.html

一、什么是AOP

AOP(Aspect Oriented Programming),即面向切面編程,可以說是OOP(Object Oriented Programming,面向對象編程)的補充和完善。OOP引入封裝、繼承、多態等概念來建立一種對象層次結構,用於模擬公共行為的一個集合。不過OOP允許開發者定義縱向的關系,但並不適合定義橫向的關系,例如日志功能。日志代碼往往橫向地散布在所有對象層次中,而與它對應的對象的核心功能毫無關系對於其他類型的代碼,如安全性、異常處理和透明的持續性也都是如此,這種散布在各處的無關的代碼被稱為橫切(cross cutting),在OOP設計中,它導致了大量代碼的重復,而不利於各個模塊的重用。

AOP技術恰恰相反,它利用一種稱為"橫切"的技術,剖解開封裝的對象內部,並將那些影響了多個類的公共行為封裝到一個可重用模塊,並將其命名為"Aspect",即切面。所謂"切面",簡單說就是那些與業務無關,卻為業務模塊所共同調用的邏輯或責任封裝起來,便於減少系統的重復代碼,降低模塊之間的耦合度,並有利於未來的可操作性和可維護性。

使用"橫切"技術,AOP把軟件系統分為兩個部分:核心關注點橫切關注點。業務處理的主要流程是核心關注點,與之關系不大的部分是橫切關注點。橫切關注點的一個特點是,他們經常發生在核心關注點的多處,而各處基本相似,比如權限認證、日志、事物。AOP的作用在於分離系統中的各種關注點,將核心關注點和橫切關注點分離開來。

二、AOP核心概念

1、橫切關注點

對哪些方法進行攔截,攔截后怎么處理,這些關注點稱之為橫切關注點

2、切面(aspect)

類是對物體特征的抽象,切面就是對橫切關注點的抽象

3、連接點(joinpoint)

被攔截到的點,因為Spring只支持方法類型的連接點,所以在Spring中連接點指的就是被攔截到的方法,實際上連接點還可以是字段或者構造器

4、切入點(pointcut)

對連接點進行攔截的定義

5、通知(advice)

所謂通知指的就是指攔截到連接點之后要執行的代碼,通知分為前置、后置、異常、最終、環繞通知五類

6、目標對象

代理的目標對象

7、織入(weave)

將切面應用到目標對象並導致代理對象創建的過程

8、引入(introduction)

在不修改代碼的前提下,引入可以在運行期為類動態地添加一些方法或字段

三、Spring對AOP的支持

Spring中AOP代理由Spring的IOC容器負責生成、管理,其依賴關系也由IOC容器負責管理。因此,AOP代理可以直接使用容器中的其它bean實例作為目標,這種關系可由IOC容器的依賴注入提供。Spring創建代理的規則為:

1、默認使用Java動態代理來創建AOP代理,這樣就可以為任何接口實例創建代理了

2、當需要代理的類不是代理接口的時候,Spring會切換為使用CGLIB代理,也可強制使用CGLIB

AOP編程其實是很簡單的事情,縱觀AOP編程,程序員只需要參與三個部分:

1、定義普通業務組件

2、定義切入點,一個切入點可能橫切多個業務組件

3、定義增強處理,增強處理就是在AOP框架為普通業務組件織入的處理動作

所以進行AOP編程的關鍵就是定義切入點和定義增強處理,一旦定義了合適的切入點和增強處理,AOP框架將自動生成AOP代理,即:代理對象的方法=增強處理+被代理對象的方法。

下面給出一個Spring AOP的.xml文件模板,名字叫做aop.xml,之后的內容都在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">
            
</beans>
復制代碼

基於Spring的AOP簡單實現

注意一下,在講解之前,說明一點:使用Spring AOP,要成功運行起代碼,只用Spring提供給開發者的jar包是不夠的,請額外上網下載兩個jar包:

1、aopalliance.jar

2、aspectjweaver.jar

開始講解用Spring AOP的XML實現方式,先定義一個接口:

1 public interface HelloWorld
2 {
3     void printHelloWorld();
4     void doPrint();
5 }

定義兩個接口實現類:

 1 public class HelloWorldImpl1 implements HelloWorld
 2 {
 3     public void printHelloWorld()
 4     {
 5         System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
 6     }
 7     
 8     public void doPrint()
 9     {
10         System.out.println("Enter HelloWorldImpl1.doPrint()");
11         return ;
12     }
13 }
 1 public class HelloWorldImpl2 implements HelloWorld
 2 {
 3     public void printHelloWorld()
 4     {
 5         System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
 6     }
 7     
 8     public void doPrint()
 9     {
10         System.out.println("Enter HelloWorldImpl2.doPrint()");
11         return ;
12     }
13 }

橫切關注點,這里是打印時間:

1 public class TimeHandler
2 {
3     public void printTime()
4     {
5         System.out.println("CurrentTime = " + System.currentTimeMillis());
6     }
7 }

有這三個類就可以實現一個簡單的Spring AOP了,看一下aop.xml的配置:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
10         
11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
14         
15         <aop:config>
16             <aop:aspect id="time" ref="timeHandler">
17                 <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
18                 <aop:before method="printTime" pointcut-ref="addAllMethod" />
19                 <aop:after method="printTime" pointcut-ref="addAllMethod" />
20             </aop:aspect>
21         </aop:config>
22 </beans>

寫一個main函數調用一下:

 1 public static void main(String[] args)
 2 {
 3     ApplicationContext ctx = 
 4             new ClassPathXmlApplicationContext("aop.xml");
 5         
 6     HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1");
 7     HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2");
 8     hw1.printHelloWorld();
 9     System.out.println();
10     hw1.doPrint();
11     
12     System.out.println();
13     hw2.printHelloWorld();
14     System.out.println();
15     hw2.doPrint();
16 }

運行結果為:

 1 CurrentTime = 1446129611993
 2 Enter HelloWorldImpl1.printHelloWorld()
 3 CurrentTime = 1446129611993
 4 
 5 CurrentTime = 1446129611994
 6 Enter HelloWorldImpl1.doPrint()
 7 CurrentTime = 1446129611994
 8 
 9 CurrentTime = 1446129611994
10 Enter HelloWorldImpl2.printHelloWorld()
11 CurrentTime = 1446129611994
12 
13 CurrentTime = 1446129611994
14 Enter HelloWorldImpl2.doPrint()
15 CurrentTime = 1446129611994

看到給HelloWorld接口的兩個實現類的所有方法都加上了代理,代理內容就是打印時間

基於Spring的AOP使用其他細節

1、增加一個橫切關注點,打印日志,Java類為:

 1 public class LogHandler
 2 {
 3     public void LogBefore()
 4     {
 5         System.out.println("Log before method");
 6     }
 7     
 8     public void LogAfter()
 9     {
10         System.out.println("Log after method");
11     }
12 }
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
10         
11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
14         <bean id="logHandler" class="com.xrq.aop.LogHandler" />
15         
16         <aop:config>
17             <aop:aspect id="time" ref="timeHandler" order="1">
18                 <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
19                 <aop:before method="printTime" pointcut-ref="addTime" />
20                 <aop:after method="printTime" pointcut-ref="addTime" />
21             </aop:aspect>
22             <aop:aspect id="log" ref="logHandler" order="2">
23                 <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
24                 <aop:before method="LogBefore" pointcut-ref="printLog" />
25                 <aop:after method="LogAfter" pointcut-ref="printLog" />
26             </aop:aspect>
27         </aop:config>
28 </beans>

測試類不變,打印結果為:

 1 CurrentTime = 1446130273734
 2 Log before method
 3 Enter HelloWorldImpl1.printHelloWorld()
 4 Log after method
 5 CurrentTime = 1446130273735
 6 
 7 CurrentTime = 1446130273736
 8 Log before method
 9 Enter HelloWorldImpl1.doPrint()
10 Log after method
11 CurrentTime = 1446130273736
12 
13 CurrentTime = 1446130273736
14 Log before method
15 Enter HelloWorldImpl2.printHelloWorld()
16 Log after method
17 CurrentTime = 1446130273736
18 
19 CurrentTime = 1446130273737
20 Log before method
21 Enter HelloWorldImpl2.doPrint()
22 Log after method
23 CurrentTime = 1446130273737

要想讓logHandler在timeHandler前使用有兩個辦法:

(1)aspect里面有一個order屬性,order屬性的數字就是橫切關注點的順序

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

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

修改一下pointcut的expression就好了:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
10         
11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
14         <bean id="logHandler" class="com.xrq.aop.LogHandler" />
15         
16         <aop:config>
17             <aop:aspect id="time" ref="timeHandler" order="1">
18                 <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.print*(..))" />
19                 <aop:before method="printTime" pointcut-ref="addTime" />
20                 <aop:after method="printTime" pointcut-ref="addTime" />
21             </aop:aspect>
22             <aop:aspect id="log" ref="logHandler" order="2">
23                 <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.do*(..))" />
24                 <aop:before method="LogBefore" pointcut-ref="printLog" />
25                 <aop:after method="LogAfter" pointcut-ref="printLog" />
26             </aop:aspect>
27         </aop:config>
28 </beans>

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

3、強制使用CGLIB生成代理

前面說過Spring使用動態代理或是CGLIB生成代理是有規則的,高版本的Spring會自動選擇是使用動態代理還是CGLIB生成代理內容,當然我們也可以強制使用CGLIB生成代理,那就是<aop:config>里面有一個"proxy-target-class"屬性,這個屬性值如果被設置為true,那么基於類的代理將起作用,如果proxy-target-class被設置為false或者這個屬性被省略,那么基於接口的代理將起作用

四、使用注解配置Spring AOP

繼續使用上面的案例的代碼

1. 定義接口:

1 package com.study.spring.springtest;
2 
3 public interface HelloWorld
4 {
5     void printHelloWorld();
6     void doPrint();
7 }

2.定義兩個接口的實現類(被代理的目標類),這里使用Spring的注解生成bean,不用再在aop.xml文件里面配置bean了

 1 package com.study.spring.springtest;
 2 
 3 import org.springframework.stereotype.Service;
 4 
 5 /**
 6  * 被代理的目標類
 7  * @author THINKPAD
 8  *
 9  */
10 @Service
11 public class HelloWorldImpl1 implements HelloWorld
12 {
13     public void printHelloWorld()
14     {
15         System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
16     }
17     
18     public void doPrint()
19     {
20         System.out.println("Enter HelloWorldImpl1.doPrint()");
21         return ;
22     }
23 }
 1 package com.study.spring.springtest;
 2 
 3 import org.springframework.stereotype.Service;
 4 
 5 /**
 6  * 被代理的目標類
 7  * @author THINKPAD
 8  *
 9  */
10 @Service
11 public class HelloWorldImpl2 implements HelloWorld {
12     public void printHelloWorld() {
13         System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
14     }
15 
16     public void doPrint() {
17         System.out.println("Enter HelloWorldImpl2.doPrint()");
18         return;
19     }
20 }

3.定義橫切關注點,@Component表示該類的實例會被Spring IOC容器管理;@Aspect表示聲明一個切面;@Before表示printTime為前置通知,通過參數execution聲明一個切點,@After表示printTime2為后置通知,通過參數execution聲明一個切點

 1 package com.study.spring.springtest;
 2 
 3 import org.aspectj.lang.annotation.After;
 4 import org.aspectj.lang.annotation.Aspect;
 5 import org.aspectj.lang.annotation.Before;
 6 import org.springframework.stereotype.Component;
 7 /**
 8  * 橫切關注點
 9  * @author THINKPAD
10  *
11  */
12 @Component
13 @Aspect
14 public class TimeHandler
15 {
16     @Before("execution(* com.study.spring.springtest.HelloWorld.*(..))")
17     public void printTime()
18     {
19         System.out.println("前置當前時間 = " + System.currentTimeMillis());
20     }
21     @After("execution(* com.study.spring.springtest.HelloWorld.*(..))")
22     public void printTime2()
23     {
24         System.out.println("后置當前時間  = " + System.currentTimeMillis());
25     }
26 }

4.aop.xml的文件現在就變得很簡潔了,內容如下

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/context
10         http://www.springframework.org/schema/context/spring-context-4.3.xsd
11         http://www.springframework.org/schema/aop
12         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
13         <!--開啟Spring注解掃描器  -->
14         <context:component-scan base-package="com.study.spring.springtest" />
15         <!-- 在配置IOC的基礎上增加了aop:aspectj-autoproxy節點,Spring框架會自動為與AspectJ切面配置的Bean創建代理,
16         proxy-target-class="true"屬性表示被代理的目標對象是一個類,
17                 而非實現了接口的類,反之proxy-target-class="false" 主要是為了選擇不同的代理方式。-->
18         <aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
19 </beans>

5.寫一個測試類

 1 package com.study.spring.springtest;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 public class TestAOP {
10     public static void main(String[] args) {
11         ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml");
12 
13         HelloWorld hw1 = (HelloWorld) ctx.getBean("helloWorldImpl1");
14         HelloWorld hw2 = (HelloWorld) ctx.getBean("helloWorldImpl2");
15         hw1.printHelloWorld();
16         System.out.println();
17         hw1.doPrint();
18 
19         System.out.println();
20         hw2.printHelloWorld();
21         System.out.println();
22         hw2.doPrint();
23     }
24 }

輸出結果:

前置當前時間 = 1507959657130
Enter HelloWorldImpl1.printHelloWorld()
后置當前時間  = 1507959657130

前置當前時間 = 1507959657130
Enter HelloWorldImpl1.doPrint()
后置當前時間  = 1507959657130

前置當前時間 = 1507959657130
Enter HelloWorldImpl2.printHelloWorld()
后置當前時間  = 1507959657130

前置當前時間 = 1507959657130
Enter HelloWorldImpl2.doPrint()
后置當前時間  = 1507959657131

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM