1. 程式人生 > >Spring4.3x教程之三AOP詳解

Spring4.3x教程之三AOP詳解

這篇文章,咱們聊聊Spring中的AOP程式設計的實現,下面是摘自官網的一些話:
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)
大意:面向方面的程式設計(AOP)通過提供另一種方法來補充面向物件的程式設計(OOP)。在OOP中,模組化的關鍵單元是類,而在AOP中,模組化的單位是方面。方面使事務管理等關注點的模組化得以實現,例如跨越多個型別和物件的事務管理。(這種擔憂經常被稱為AOP文學中的橫切關注點。)
AOP is used in the Spring Framework to:
1、provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management.
2、allow users to implement custom aspects, complementing their use of OOP with AOP.
AOP 是在 Spring 框架使用的…
1、提供宣告式企業服務,特別是作為EJB宣告服務的替代。最重要的服務是宣告式事務管理。
2、允許使用者實現自定義方面,並與AOP一起使用OOP。

OOP:Object-Oriented Programming 面向物件程式設計
就是萬事萬物皆物件
類和物件
AOP:Aspect-Oriented Programming面向切面程式設計
我們以橫切面來進行開發
切入點和切面
比如我們使用OOP的時候,多個類之間的關係一般都是縱向關係。那麼如果我們只關心具體的某些方法呢(這些方法在不同的類中)?OOP還能很好的搞定嗎?再比如一個類中有10個屬性,但是我們只需要其中的一個屬性,通過OOP那麼這10個屬性你都需要擁有,會不會很浪費呢?
總而言之OOP的缺陷:
1、縱向關係
2、最小分割的是類
而AOP就是對OOP的彌補:
1、橫向關係
2、以面為最小單位,至於說面的大小完全取決於切入點的寫法
歸根結底:AOP可以讓我們在不改變原始碼的情況下對某些方法的功能做出改變。
AOP的切入點可以是屬性、方法、構造器,但是Spring引用時只是保留了方法。所以Spring AOP就是基於方法的切面程式設計的實現。
那麼我們在使用AOP的時候,需要明白幾個核心概念:
1、Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
1、切面:對跨多個類進行切割的關注的模組化。事務管理是企業Java應用程式橫切關注的一個很好的例子。在Spring AOP中,方面是使用常規類(基於模式的方法)實現的,或者使用@ aspect註釋(@ aspectj樣式)註釋的規則類。
2、Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
2、連線點:在執行程式時的一個點,例如執行方法或處理異常。在Spring AOP中,連線點總是表示方法執行。
3、Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. (Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.
3、通知:在特定連線點上的一個方面所採取的行動。不同型別的建議包括“around”,“before”和“after”建議。(以下是建議型別。)許多AOP框架,包括Spring,將一個建議作為攔截器,在連線點周圍維護一個攔截器鏈。
4、Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
4、切入點:匹配連線點的謂詞。建議與切入點表示式相關聯,並在切入點(例如,具有特定名稱的方法的執行)匹配的任何連線點上執行。連線點與切入點表示式匹配的概念是AOP的核心,Spring在預設情況下使用AspectJ切點表示式語言。
5、Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
5、引入:代表型別宣告其他方法或欄位。Spring AOP允許您向任何被建議的物件引入新的介面(以及相應的實現)。例如,您可以使用介紹使bean實現一個IsModified介面,以簡化快取。(在AspectJ社群中,介紹稱為跨型別宣告。)
6、Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
6、目標類:也叫委託類:被一個或多個方面建議的物件。也稱為被建議的物件。由於Spring AOP是使用執行時代理實現的,所以這個物件將永遠是一個代理物件。
7、AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
7、代理類:一個由AOP框架建立的物件,以實現方面契約(通知方法執行等)。在Spring框架中,AOP代理將是一個JDK動態代理或CGLIB代理。
8、Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
8、織入:將各方面與其他應用程式型別或物件連結起來,建立一個建議物件。這可以在編譯時完成(例如,使用AspectJ編譯器),載入時間,或者執行時。與其他純Java AOP框架一樣,Spring AOP在執行時執行編織
上述就是AOP的八大核心概念:
簡單來講:
我們需要建立通知類也就是我們需要對方法的額外實現的功能
然後我們再定義切入點,目的是獲取跟切入點匹配的切面。有了切面我們就可以在連線點處設定什麼時候執行我們通知中的方法。那如何執行通知中的方法呢,藉助於代理模式實現的代理類。
使用Spring AOP的步驟:
1、建立通知類

public class SQLTime {

    long start;
    //之前記錄
    public void startTime() {
        start=System.currentTimeMillis();
    }

    //之後結果
    public void endTime() {
        System.out.println("本次時間:"+(System.currentTimeMillis()-start));
    }
}

2、配置AOP
在applicationContext.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" 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"> <!-- 配置dao物件 --> <bean id="dao1" class="cn.code404.dao.UserDao" scope="prototype"/> <!--配置service物件 --> <bean id="service1" class="cn.code404.service.UserService" scope="prototype"> <property name="dao" ref="dao1"></property> </bean> <!--統計dao包下的方法的執行次數 --> <!--1、配置通知類物件 --> <bean id="advice1" class="cn.code404.advice.SQLTime"></bean> <!-- aop切面的配置資訊 --> <aop:config> <!--定義切入點 切入點的表示式的意思: 1、* 返回值型別 2、包名 * 3、類名 * 4、方法名 * --> <aop:pointcut expression="execution(* cn.code404.dao.*Dao.*(..))" id="p1"/> <!--建立橫切面 --> <aop:aspect ref="advice1" id="ap1"> <!--配置通知執行的時機 前:before 後:after 環繞:前和後 成功返回:after-returning 返回異常:after-throwing --> <aop:before method="startTime" pointcut-ref="p1"/> <aop:after method="endTime" pointcut-ref="p1"/> </aop:aspect> </aop:config> </beans>

上述就是使用AOP實現對查詢方法的只需時間的統計。如果不是呀AOP那麼需要在dao層的select語句之前和之後修改記錄時間。可是使用了AOP我們就可以不用去改變Dao層的程式碼只是在執行方法時自動的將通知中的方法給執行就可以了。
其實用好切面就記住三個單詞就夠了:
what:幹什麼
使用AOP要達到什麼目的,也就是我們的通知
where:在哪裡
對哪些方法加通知:切入點
when:什麼時候
在什麼時候去執行通知的方法
也就是配置切面的通知出現的時機,前、後、異常、環繞等。