當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
spring(4)面向切面的Spring(AOP)
生活随笔
收集整理的這篇文章主要介紹了
spring(4)面向切面的Spring(AOP)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【0】README
1)本文部分文字描述轉自:“Spring In Action(中/英文版)”,旨在review ?“spring(4)面向切面的Spring(AOP)”?的相關知識;
2)在軟件開發中,散布于應用中多處的功能被稱為橫切關注點。通常來講,這些橫切關注點從概念上是與應用的業務邏輯相分離的(但是往往會直接嵌入到應用的業務邏輯中)。把這些橫切關注點與業務邏輯相分離正是面向切面編程(AOP)所要解決的問題;(干貨——引入橫切關注點及其所要解決的問題)
3)要知道,DI有助于應用對象之間的解耦,而AOP 可以實現橫切關注點與它們所影響的對象之間的解耦;(干貨——DI 和 AOP 的作用)
4)本文內容概覽:
4.1)暫時了Spring對切面的支持,包括如何把普通類聲明為一個切面和如何使用注解創建切面; 4.2)除此之外,還可以看到 AspectJ——另一種流行的AOP實現——如何補充Spring AOP的功能;(干貨——引入AspectJ框架)
【1】什么是面向切面編程 1)problem+solution: 1.1)problem:如果要重用通用功能的話,最常見的技術是繼承或委托。但是,如果在整個應用中都使用相同的基類,繼承往往會導致一個脆弱的對象體系; 1.2)solution:切面提供了取代繼承和委托的另一種可選方案; 2)切面:橫切關注點可以被模塊化為特殊的類,這些類被稱為切面;這樣做有兩個好處(merits)(干貨——切面的定義) m1)現在每個關注點都集中于一個地方,而不是分散到多處; m2)服務模塊更加簡潔了,因為它們只包含主要關注點的代碼,而次要關注點的代碼被轉移到切面中了;
【1.1】定義AOP術語 1)描述切面的術語有:通知,切點,連接點; 1.1)通知(Advice):切面的工作被稱為通知;通知定義了切面是什么以及何時使用;(5中類型的通知:前置通知,后置通知,返回通知,異常通知,環繞通知)
1.2)連接點(Join point):是在應用執行過程中能夠插入切面的一個點; 1.3)切點(Pointcut):如果說通知定義了切面是什么和何時執行的話,那么切點就定義了 何處(在何處執行),切點的定義會匹配通知所要織入的一個或多個連接點; 1.4)切面(Aspect):切面是通知和切點的結合。通知和切點共同定義了切面的全部內容——它是什么? 1.5)引入(Introduction):引入允許我們向現有的類添加新方法或屬性; 1.6)織入(Weaving):織入是吧切面應用到目標對象并創建新的代理對象的過程;切面在指定的連接點被織入到目標對象中。在目標對象的生命周期里有多個點可以進行織入: peroid1)編譯期:切面在目標類編譯時被織入;AspectJ的織入編譯器就是以這種方式織入切面的; peroid2)類加載期:切面在目標類加載到 jvm 時 被織入;這種方式需要特殊的類加載器(ClassLoader),它可以在目標類被引入應用之前增強該目標類的字節碼;AspectJ 5 的加載時織入(load-time weaving,LTW)就支持以這種方式織入切面; period3)運行期:切面在應用運行的某個時刻被織入;一般case下,在織入切面時,AOP 容器會為目標對象動態地創建一個代理對象。Spring AOP 就是以這種方式織入切面的;
【1.2】Spring對AOP 的支持 1)Spring 和 AspectJ 之間有大量的協作,而且Spring 對 AOP 的支持在很多方面借鑒了 AspectJ 項目; 2)spring 提供了4中類型的 AOP支持: type1)基于代理的經典 spring AOP; type2)純 POJO 切面; type3)@AspectJ 注解驅動的切面; type4)注入式 AspectJ 切面(適用于spring 各種version); Attention) A1)前三種都是 spring aop 實現的變體,spring aop 構建在動態代理基礎之上:因此,spring 對 aop的支持局限于方法攔截;(干貨——spring 對 aop的支持局限于方法攔截) A2)spring 借鑒了AspectJ 的切面,以提供注解驅動的AOP。本質上,它依然是 spring 基于代理的aop,但是編程模型幾乎與編寫成熟的 AspectJ 注解切面完全一致。這種aop 風格的好處在于能夠不使用XML 來完成功能; 3)spring 在運行時通知對象:通過在代理類中包裹切面,spring 在運行期吧切面織入到 spring管理的bean中。 如下圖所示。代理類封裝了目標類,并攔截被通知方法的調用,再把調用轉發給真正的目標bean。當代理攔截到方法調用時,在調用目標bean 方法之前,會執行切面邏輯;
4)spring 只支持方法級別的連接點: 通過使用各種aop 方案可以支持多種連接點模型; 4.1)因為spring基于動態代理,所以spring 只支持方法連接點。這與一些其他的AOP 框架是不同的,例如 AspectJ 和 JBoss,除了方法切點外,它們還提供了字段和構造器接入點;(干貨——因為spring基于動態代理,所以spring 只支持方法連接點) 4.2)方法攔截可以滿足絕大部分的需求;如果需要方法攔截之外的連接點攔截功能,可以利用 Aspect 來補充 spring aop 的功能;
【2】通過切點來選擇連接點 1)關于spring aop 的AspectJ 切點,最重要的一點是:spring僅僅支持AspectJ 切點指示器的一個子集; 2)review:spring是基于代理的,而某些切點表達式是與基于代理的aop 無關的,下表列出了 spring aop 所支持的 AspectJ 切點指示器;
Attention)只有 execution指示器: 是實際執行匹配的,而其他的指示器都是用來限制匹配的;它是最主要使用的指示器;
【2.1】編寫切點 1)需要有個主題來定義切面的切點: public interface Performance {public void perform(); }2)表達式execution(* concert.Performance.perform(..)):這個表達式能夠設置當 perform()方法執行時觸發通知的調用;
3)假設我們需要匹配的切點僅匹配 concert 包,在此case下,可以使用 ?within() 指示器來限制匹配, 如下圖所示;
【2.2】在切點中選擇bean 1)bean()指示器:spring 引入了新的bean()指示器,它允許我們在切點表達式中使用 bean ?的ID 來標識 bean。(干貨——引入指示器的概念) 2)看個荔枝: execution(* concert.Performance.perform()) ?and bean('jaychou') :我們希望在執行Performance.perform方法時應用通知,但限定bean的ID為?jaychou; execution(* concert.Performance.perform()) ?and !bean('jaychou'):?我們希望在執行Performance.perform方法時應用通知,但限定bean的ID不為?jaychou;
【3】使用注解創建切面 1)intro:使用注解來創建切面是 AspectJ 5 所引入 的關鍵特性;
【3.1】定義切面 1)看個荔枝:將考生定義為一個切面; @Aspect public class Examinee { // 考生@Before("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void checkIdentity() { // 身份審查System.out.println("please show us your admission ticket.");}@Before("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void checkSecurity() { // 安檢System.out.println("please accept electronic equipment inspection.");}@AfterReturning("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void handinPaper() { // 交卷System.out.println("please hand in an examination paper.");}@AfterThrowing("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void cancelQualification() { // 取消考試資格System.out.println("cancel the exam qualification");} } 對以上代碼的分析(Analysis): A1)spring使用了 AspectJ 注解來聲明通知方法, 如下表所示:
A2)上面的注解都給定了一個切點表達式作為它的值,且這4個切點表達式都是相同的,其實它們可以設置成為不同的切點表達式;
3)problem+solution: 3.1)problem:相同的切點表達式出現了四遍,這可是不光彩的事情; 3.2)solution:引入了 @PointCut注解, 該注解能夠在一個 @AspectJ 切面內定義可重用個切點; @Aspect public class ExamineeVersion2 {@Pointcut("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void chineseExamination(){}@Before("chineseExamination()")public void checkIdentity() { // 身份審查System.out.println("please show us your admission ticket.");}@Before("chineseExamination()")public void checkSecurity() { // 安檢System.out.println("please accept electronic equipment inspection.");}@AfterReturning("chineseExamination()")public void handinPaper() { // 交卷System.out.println("please hand in an examination paper.");}@AfterThrowing("chineseExamination()")public void cancelQualification() { // 取消考試資格System.out.println("cancel the exam qualification");} } 對以上代碼的分析(Analysis): A1)在 Examinee中,chineseExamination()方法使用了 @Pointcut 注解,為@Pointcut注解設置的值是一個切點表達式; A2)實際上擴展了切點表達式語言,這就可以在 任何的切點表達式中使用?chineseExamination()方法了;
4)problem+solution: 4.1)problem:如果僅僅是以上代碼的話,即便使用了AspectJ 注解,但它也不會被視為切面,這些注解不會解析,也不會創建將其轉換為切面的代理; 4.2)solution:如果使用JavaConfig的話,可以在配置類的類級別上通過使用 @EnableAspectJAutoProxy 注解啟用自動代理功能;(干貨——@EnableAspectJAutoProxy 注解的作用) @Configuration @EnableAspectJAutoProxy @ComponentScan public class ExaminationConfig {@Beanpublic Examinee getExaminee() {return new Examinee("xiaotang");} } 4.3)如果使用XML配置類裝配bean的話,使用 spring aop命名空間中的 <aop:aspectj-autoproxy> 元素:
Attention)? A1)不管使用JavaConfig 還是 XML配置來裝配:AspectJ 自動代理都會為使用 @AspectJ 注解的bean創建一個代理,這個代理會圍繞著所有該切面的切點所匹配的bean; A2)在這種case下,將會為 Examination bean創建一個代理,Examinee類中的通知方法將會在 chineseExamination() 方法調用前后執行; A3)spring的 AspectJ 自動代理僅僅是使用 @AspectJ 作為創建切面的指導,切面依然是基于代理的;本質上,它依然是 spring基于代理的切面;
【3.2】創建環繞通知 1)intro:環繞通知是最強大的通知類型。它能夠讓你所編寫的邏輯將被通知的目標方法完全包裝起來。實際上就想是在一個通知方法中通知編寫前置通知和后置通知; 2)看個荔枝:重寫 Eaxminee 切面; // 考生(就是一個切面) @Aspect public class ExamineeVersion3 {@Pointcut("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void chineseExamination() {}@Around("chineseExamination()")public void doChineseExamination(ProceedingJoinPoint jp) {try {System.out.println("please show us your admission ticket.");System.out.println("please accept electronic equipment inspection.");jp.proceed();System.out.println("please hand in an examination paper.");} catch (Throwable e) {System.out.println("cancel the exam qualification");}} } 對以上代碼的分析(Analysis): A1)@Around注解表明?doChineseExamination() 方法會作為?chineseExamination() 切點的環繞通知;(干貨——@Around注解的作用) A2)別忘記調用 ProceedingJoinPoint.proceed()方法,如果不調用這個方法的話,那么你的通知實際上會阻塞對被通知方法的調用; A3)當然,你可以不調用ProceedingJoinPoint.proceed()方法,你也可以在通知中對它進行多次調用;
【3.3】處理通知中的參數 1)除了環繞通知,我們編寫的其他通知不需要關注傳遞給被通知方法的任意參數; 2)如果切面所通知的方法確實有參數該怎么辦?切面能訪問和使用傳遞給被通知方法的參數嗎? 3)看個荔枝:
對以上代碼的分析(Analysis): A1)這里的不同點在于切點還聲明了要提供給通知方法的參數;
A2)關注 args(trackNumber))限定符:它表明傳遞給 playTrack()方法的int類型參數也會傳遞到通知里面去,參數的名稱 trackNumber 也與切點方法簽名中的參數相匹配; A3)這個參數會傳遞到通知方法中:該方法是通過 @Before 注解和命名切點 trackPlayed(trackNumber)定義的。切點定義中的參數與切點方法中的參數名稱是一樣的,這樣就完成了從命名切點到通知方法的參數轉移;
@Aspect public class ExamineeArgs {private String name;public ExamineeArgs(String name) {this.name = name;}@Pointcut("execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int)) "+ "&& args(examSiteCode)")public void myGetExamineeNumber(int examSiteCode) {}@Before("myGetExamineeNumber(examSiteCode)")public void checkIdentity(int examSiteCode) { // 身份審查System.out.println("@Before: your exam site code is " + examSiteCode);} } 【3.4】通過注解引入新功能 1)intro:切面能夠為現有的方法增加新功能,利用aop概念,切面與可以為 spring bean 添加新方法;
2)當引入接口的方法被調用時,代理會把此調用委托給實現了新接口的某個其他對象。實際上,一個bean的實現被拆分到了多個類中;(干貨——一個spring bean的實現被拆分到了多個類中) 3)借助于aop 的引入功能,可以不必在設計上妥協或侵入性地改變現有的實現。為了實現該功能,我們要創建一個新切面; @Aspect public class ExamineeArgs {private String name;public ExamineeArgs(String name) {this.name = name;}@Pointcut("execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int)) "+ "&& args(examSiteCode)")public void myGetExamineeNumber(int examSiteCode) { }@Before("myGetExamineeNumber(examSiteCode)")public void checkIdentity(int examSiteCode) { // 身份審查System.out.println("@Before: your exam site code is " + examSiteCode);} }// 高考 public class CollegeEntraceExamination {public CollegeEntraceExamination() { }public void chineseExamination() {System.out.println("chinese examination is underway.");}public int getExamineeNumber(int examSiteCode) {return 1000;} } //---------------------------------------我是分割線. @Aspect public class AdditionExaminationIntroducer{@DeclareParents(value="com.spring.chapter4.CollegeEntraceExamination.chineseExamination+",defaultImpl=AdditionExaminationImpl.class)public static AddtionExamination addtionExamination; } public interface AddtionExamination {void doAddtionalExamination(); } public class AdditionExaminationImpl implements AddtionExamination{@Overridepublic void doAddtionalExamination() {System.out.println("do additional questions as possible as you can.");} } 對以上代碼的分析(Analysis):
A1)這個切面與以往切面不同的是:它并沒有前置,后置等通知,而是通過 @DeclareParents注解將?AddtionExamination? 接口引入到?CollegeEntraceExamination bean中; A2)@DeclareParents注解由3個部分組成:(干貨——@DeclareParents注解的作用) part1)value屬性:指定了哪種類型的bean 要引入該接口; part2)defaultImpl:指定了為引入功能提供實現的類; part3)@DeclareParents注解所標注的靜態屬性:指明了要引入的接口; A3)和其它切面一樣,需要在spring 應用中將 AdditionExaminationIntroducer 聲明為 一個 bean; <bean class="com.spring.chapter4.AdditionExaminationIntroducer" /> spring 的自動代理機制將會獲取到它的聲明,但 spring 發現一個bean使用 @Aspect注解時,spring就會創建一個代理,然后將調用委托給被代理bean 或被引入的實現,這取決于調用的方法屬于被代理的bean 還是屬于被引入的接口;(干貨——這解釋了為什么一個spring bean的實現被拆分到了多個類中的問題)
對上圖的分析(Analysis):我們看到,即使CollegeEntraceExamination 并沒有實現?AddtionExamination接口,但是通過創建新切面為前者添加了新方法,CollegeEntraceExamination?就可以調用了doAddtionalExamination()方法了;
4)面向注解的切面聲明有一個明顯的劣勢:你必須能夠為通知類添加注解。為了做到這一點,必須要有源碼;如果沒有源碼,或不想將 AspectJ 注解放到你的代碼中,可以使用 spring XML 配置文件中聲明切面;(干貨——面向注解的切面聲明有一個明顯的劣勢)
【4】在XML 中聲明切面 1)之前有這樣一個rule:基于注解的bean裝配要優于基于JavaConfig 的裝配,基于JavaConfig的裝配 要優于基于XML的配置裝配; 2)但是,如果需要聲明切面,但又不能為通知類添加注解的時候,那么就必須轉向XML 配置了; 3)spring 的aop 配置元素能夠以非侵入性的方式聲明切面
【4.1】聲明前置和后置通知 1)通過XML 將無注解的 Examinee 聲明為切面 <aop:config><aop:aspect ref="examinee"><aop:beforepointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="checkIdentity"/><aop:beforepointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="checkIdentity"/><aop:after-returningpointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="handinPaper"/><aop:after-throwingpointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="cancelQualification"/></aop:aspect> </aop:config> 2)使用<aop:pointcut> 定義命名切點 <aop:config><aop:aspect ref="examinee"><aop:pointcutid="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:beforepointcut-ref="chineseExamination"method="checkIdentity"/><aop:beforepointcut-ref="chineseExamination"method="checkIdentity"/><aop:after-returningpointcut-ref="chineseExamination"method="handinPaper"/><aop:after-throwingpointcut-ref="chineseExamination"method="cancelQualification"/></aop:aspect> </aop:config> 圖片t18
Attention)spring4-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXML"><aop:pointcut id="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:before pointcut-ref="chineseExamination" method="checkIdentity" /><aop:before pointcut-ref="chineseExamination" method="checkSecurity" /><aop:after-returning pointcut-ref="chineseExamination" method="handinPaper" /><aop:after-throwing pointcut-ref="chineseExamination" method="cancelQualification" /></aop:aspect></aop:config> </beans> 【4.2】在XML配置元素中聲明環繞通知 step1)attendChineseExamination()方法提供了aop環繞通知; // 考生(就是一個切面) public class ExamineeAroundXML {private String name;public ExamineeAroundXML(String name) {this.name = name;}public void attendChineseExamination(ProceedingJoinPoint jp) {try {System.out.println("AroundXML@Before: please show us your admission ticket.");System.out.println("AroundXML@Before: please accept electronic equipment inspection.");jp.proceed();System.out.println("AroundXML@AfterReturn: please hand in an examination paper.");} catch (Throwable e) {System.out.println("AroundXML@AfterThrowing: cancel the exam qualification");}} } step2)在XML 中使用 <aop:around>元素聲明環繞通知 <aop:config><aop:aspect ref="audience"><aop:pointcutid="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:aroundpointcut-ref="chineseExamination"method="attendChineseExamination"/></aop:aspect> </aop:config> 圖片t19
【4.3】 為通知傳遞參數(在XML中將ExamineeXMLArgs 配置為參數化的切面 ) 圖片t20
@Configuration @ImportResource("classpath:com/spring/chapter4/spring4-args-config.xml") public class ExaminationConfig {@Beanpublic CollegeEntraceExamination getExamination() {return new CollegeEntraceExamination();}@Bean(name="examineeXMLArgs")public ExamineeXMLArgs getExamineeXMLArgs() {return new ExamineeXMLArgs("xiaotang");} } spring4-args-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXMLArgs"><aop:pointcut id="getExamineeNumber"expression="execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int))and args(examSiteCode)" /><aop:before pointcut-ref="getExamineeNumber" method="checkIdentity"/></aop:aspect></aop:config> </beans>
【4.4】通過XML為切面引入新功能 圖片(t21)
@Configuration @ImportResource("classpath:com/spring/chapter4/spring4-args-intro-config.xml") public class ExaminationConfig {@Beanpublic CollegeEntraceExamination getExamination() {return new CollegeEntraceExamination();}@Bean(name="examineeXMLArgs")public ExamineeXMLArgs getExamineeXMLArgs() {return new ExamineeXMLArgs("xiaotang");} } spring4-args-intro-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXMLArgs"><aop:pointcut id="getExamineeNumber"expression="execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int))and args(examSiteCode)" /><aop:before pointcut-ref="getExamineeNumber" method="checkIdentity"/></aop:aspect><aop:aspect><aop:declare-parents types-matching="com.spring.chapter4.CollegeEntraceExamination+" implement-interface="com.spring.chapter4.AddtionExamination" default-impl="com.spring.chapter4.AdditionExaminationImpl"<!-- delegate-ref="additionExaminationImpl" 前提是spring容器中有additionExaminationImpl bean--> /></aop:aspect></aop:config> </beans>
【1】什么是面向切面編程 1)problem+solution: 1.1)problem:如果要重用通用功能的話,最常見的技術是繼承或委托。但是,如果在整個應用中都使用相同的基類,繼承往往會導致一個脆弱的對象體系; 1.2)solution:切面提供了取代繼承和委托的另一種可選方案; 2)切面:橫切關注點可以被模塊化為特殊的類,這些類被稱為切面;這樣做有兩個好處(merits)(干貨——切面的定義) m1)現在每個關注點都集中于一個地方,而不是分散到多處; m2)服務模塊更加簡潔了,因為它們只包含主要關注點的代碼,而次要關注點的代碼被轉移到切面中了;
【1.1】定義AOP術語 1)描述切面的術語有:通知,切點,連接點; 1.1)通知(Advice):切面的工作被稱為通知;通知定義了切面是什么以及何時使用;(5中類型的通知:前置通知,后置通知,返回通知,異常通知,環繞通知)
1.2)連接點(Join point):是在應用執行過程中能夠插入切面的一個點; 1.3)切點(Pointcut):如果說通知定義了切面是什么和何時執行的話,那么切點就定義了 何處(在何處執行),切點的定義會匹配通知所要織入的一個或多個連接點; 1.4)切面(Aspect):切面是通知和切點的結合。通知和切點共同定義了切面的全部內容——它是什么? 1.5)引入(Introduction):引入允許我們向現有的類添加新方法或屬性; 1.6)織入(Weaving):織入是吧切面應用到目標對象并創建新的代理對象的過程;切面在指定的連接點被織入到目標對象中。在目標對象的生命周期里有多個點可以進行織入: peroid1)編譯期:切面在目標類編譯時被織入;AspectJ的織入編譯器就是以這種方式織入切面的; peroid2)類加載期:切面在目標類加載到 jvm 時 被織入;這種方式需要特殊的類加載器(ClassLoader),它可以在目標類被引入應用之前增強該目標類的字節碼;AspectJ 5 的加載時織入(load-time weaving,LTW)就支持以這種方式織入切面; period3)運行期:切面在應用運行的某個時刻被織入;一般case下,在織入切面時,AOP 容器會為目標對象動態地創建一個代理對象。Spring AOP 就是以這種方式織入切面的;
【1.2】Spring對AOP 的支持 1)Spring 和 AspectJ 之間有大量的協作,而且Spring 對 AOP 的支持在很多方面借鑒了 AspectJ 項目; 2)spring 提供了4中類型的 AOP支持: type1)基于代理的經典 spring AOP; type2)純 POJO 切面; type3)@AspectJ 注解驅動的切面; type4)注入式 AspectJ 切面(適用于spring 各種version); Attention) A1)前三種都是 spring aop 實現的變體,spring aop 構建在動態代理基礎之上:因此,spring 對 aop的支持局限于方法攔截;(干貨——spring 對 aop的支持局限于方法攔截) A2)spring 借鑒了AspectJ 的切面,以提供注解驅動的AOP。本質上,它依然是 spring 基于代理的aop,但是編程模型幾乎與編寫成熟的 AspectJ 注解切面完全一致。這種aop 風格的好處在于能夠不使用XML 來完成功能; 3)spring 在運行時通知對象:通過在代理類中包裹切面,spring 在運行期吧切面織入到 spring管理的bean中。 如下圖所示。代理類封裝了目標類,并攔截被通知方法的調用,再把調用轉發給真正的目標bean。當代理攔截到方法調用時,在調用目標bean 方法之前,會執行切面邏輯;
4)spring 只支持方法級別的連接點: 通過使用各種aop 方案可以支持多種連接點模型; 4.1)因為spring基于動態代理,所以spring 只支持方法連接點。這與一些其他的AOP 框架是不同的,例如 AspectJ 和 JBoss,除了方法切點外,它們還提供了字段和構造器接入點;(干貨——因為spring基于動態代理,所以spring 只支持方法連接點) 4.2)方法攔截可以滿足絕大部分的需求;如果需要方法攔截之外的連接點攔截功能,可以利用 Aspect 來補充 spring aop 的功能;
【2】通過切點來選擇連接點 1)關于spring aop 的AspectJ 切點,最重要的一點是:spring僅僅支持AspectJ 切點指示器的一個子集; 2)review:spring是基于代理的,而某些切點表達式是與基于代理的aop 無關的,下表列出了 spring aop 所支持的 AspectJ 切點指示器;
Attention)只有 execution指示器: 是實際執行匹配的,而其他的指示器都是用來限制匹配的;它是最主要使用的指示器;
【2.1】編寫切點 1)需要有個主題來定義切面的切點: public interface Performance {public void perform(); }2)表達式execution(* concert.Performance.perform(..)):這個表達式能夠設置當 perform()方法執行時觸發通知的調用;
3)假設我們需要匹配的切點僅匹配 concert 包,在此case下,可以使用 ?within() 指示器來限制匹配, 如下圖所示;
【2.2】在切點中選擇bean 1)bean()指示器:spring 引入了新的bean()指示器,它允許我們在切點表達式中使用 bean ?的ID 來標識 bean。(干貨——引入指示器的概念) 2)看個荔枝: execution(* concert.Performance.perform()) ?and bean('jaychou') :我們希望在執行Performance.perform方法時應用通知,但限定bean的ID為?jaychou; execution(* concert.Performance.perform()) ?and !bean('jaychou'):?我們希望在執行Performance.perform方法時應用通知,但限定bean的ID不為?jaychou;
【3】使用注解創建切面 1)intro:使用注解來創建切面是 AspectJ 5 所引入 的關鍵特性;
【3.1】定義切面 1)看個荔枝:將考生定義為一個切面; @Aspect public class Examinee { // 考生@Before("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void checkIdentity() { // 身份審查System.out.println("please show us your admission ticket.");}@Before("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void checkSecurity() { // 安檢System.out.println("please accept electronic equipment inspection.");}@AfterReturning("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void handinPaper() { // 交卷System.out.println("please hand in an examination paper.");}@AfterThrowing("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void cancelQualification() { // 取消考試資格System.out.println("cancel the exam qualification");} } 對以上代碼的分析(Analysis): A1)spring使用了 AspectJ 注解來聲明通知方法, 如下表所示:
A2)上面的注解都給定了一個切點表達式作為它的值,且這4個切點表達式都是相同的,其實它們可以設置成為不同的切點表達式;
3)problem+solution: 3.1)problem:相同的切點表達式出現了四遍,這可是不光彩的事情; 3.2)solution:引入了 @PointCut注解, 該注解能夠在一個 @AspectJ 切面內定義可重用個切點; @Aspect public class ExamineeVersion2 {@Pointcut("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void chineseExamination(){}@Before("chineseExamination()")public void checkIdentity() { // 身份審查System.out.println("please show us your admission ticket.");}@Before("chineseExamination()")public void checkSecurity() { // 安檢System.out.println("please accept electronic equipment inspection.");}@AfterReturning("chineseExamination()")public void handinPaper() { // 交卷System.out.println("please hand in an examination paper.");}@AfterThrowing("chineseExamination()")public void cancelQualification() { // 取消考試資格System.out.println("cancel the exam qualification");} } 對以上代碼的分析(Analysis): A1)在 Examinee中,chineseExamination()方法使用了 @Pointcut 注解,為@Pointcut注解設置的值是一個切點表達式; A2)實際上擴展了切點表達式語言,這就可以在 任何的切點表達式中使用?chineseExamination()方法了;
4)problem+solution: 4.1)problem:如果僅僅是以上代碼的話,即便使用了AspectJ 注解,但它也不會被視為切面,這些注解不會解析,也不會創建將其轉換為切面的代理; 4.2)solution:如果使用JavaConfig的話,可以在配置類的類級別上通過使用 @EnableAspectJAutoProxy 注解啟用自動代理功能;(干貨——@EnableAspectJAutoProxy 注解的作用) @Configuration @EnableAspectJAutoProxy @ComponentScan public class ExaminationConfig {@Beanpublic Examinee getExaminee() {return new Examinee("xiaotang");} } 4.3)如果使用XML配置類裝配bean的話,使用 spring aop命名空間中的 <aop:aspectj-autoproxy> 元素:
Attention)? A1)不管使用JavaConfig 還是 XML配置來裝配:AspectJ 自動代理都會為使用 @AspectJ 注解的bean創建一個代理,這個代理會圍繞著所有該切面的切點所匹配的bean; A2)在這種case下,將會為 Examination bean創建一個代理,Examinee類中的通知方法將會在 chineseExamination() 方法調用前后執行; A3)spring的 AspectJ 自動代理僅僅是使用 @AspectJ 作為創建切面的指導,切面依然是基于代理的;本質上,它依然是 spring基于代理的切面;
【3.2】創建環繞通知 1)intro:環繞通知是最強大的通知類型。它能夠讓你所編寫的邏輯將被通知的目標方法完全包裝起來。實際上就想是在一個通知方法中通知編寫前置通知和后置通知; 2)看個荔枝:重寫 Eaxminee 切面; // 考生(就是一個切面) @Aspect public class ExamineeVersion3 {@Pointcut("execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))")public void chineseExamination() {}@Around("chineseExamination()")public void doChineseExamination(ProceedingJoinPoint jp) {try {System.out.println("please show us your admission ticket.");System.out.println("please accept electronic equipment inspection.");jp.proceed();System.out.println("please hand in an examination paper.");} catch (Throwable e) {System.out.println("cancel the exam qualification");}} } 對以上代碼的分析(Analysis): A1)@Around注解表明?doChineseExamination() 方法會作為?chineseExamination() 切點的環繞通知;(干貨——@Around注解的作用) A2)別忘記調用 ProceedingJoinPoint.proceed()方法,如果不調用這個方法的話,那么你的通知實際上會阻塞對被通知方法的調用; A3)當然,你可以不調用ProceedingJoinPoint.proceed()方法,你也可以在通知中對它進行多次調用;
【3.3】處理通知中的參數 1)除了環繞通知,我們編寫的其他通知不需要關注傳遞給被通知方法的任意參數; 2)如果切面所通知的方法確實有參數該怎么辦?切面能訪問和使用傳遞給被通知方法的參數嗎? 3)看個荔枝:
對以上代碼的分析(Analysis): A1)這里的不同點在于切點還聲明了要提供給通知方法的參數;
A2)關注 args(trackNumber))限定符:它表明傳遞給 playTrack()方法的int類型參數也會傳遞到通知里面去,參數的名稱 trackNumber 也與切點方法簽名中的參數相匹配; A3)這個參數會傳遞到通知方法中:該方法是通過 @Before 注解和命名切點 trackPlayed(trackNumber)定義的。切點定義中的參數與切點方法中的參數名稱是一樣的,這樣就完成了從命名切點到通知方法的參數轉移;
@Aspect public class ExamineeArgs {private String name;public ExamineeArgs(String name) {this.name = name;}@Pointcut("execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int)) "+ "&& args(examSiteCode)")public void myGetExamineeNumber(int examSiteCode) {}@Before("myGetExamineeNumber(examSiteCode)")public void checkIdentity(int examSiteCode) { // 身份審查System.out.println("@Before: your exam site code is " + examSiteCode);} } 【3.4】通過注解引入新功能 1)intro:切面能夠為現有的方法增加新功能,利用aop概念,切面與可以為 spring bean 添加新方法;
2)當引入接口的方法被調用時,代理會把此調用委托給實現了新接口的某個其他對象。實際上,一個bean的實現被拆分到了多個類中;(干貨——一個spring bean的實現被拆分到了多個類中) 3)借助于aop 的引入功能,可以不必在設計上妥協或侵入性地改變現有的實現。為了實現該功能,我們要創建一個新切面; @Aspect public class ExamineeArgs {private String name;public ExamineeArgs(String name) {this.name = name;}@Pointcut("execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int)) "+ "&& args(examSiteCode)")public void myGetExamineeNumber(int examSiteCode) { }@Before("myGetExamineeNumber(examSiteCode)")public void checkIdentity(int examSiteCode) { // 身份審查System.out.println("@Before: your exam site code is " + examSiteCode);} }// 高考 public class CollegeEntraceExamination {public CollegeEntraceExamination() { }public void chineseExamination() {System.out.println("chinese examination is underway.");}public int getExamineeNumber(int examSiteCode) {return 1000;} } //---------------------------------------我是分割線. @Aspect public class AdditionExaminationIntroducer{@DeclareParents(value="com.spring.chapter4.CollegeEntraceExamination.chineseExamination+",defaultImpl=AdditionExaminationImpl.class)public static AddtionExamination addtionExamination; } public interface AddtionExamination {void doAddtionalExamination(); } public class AdditionExaminationImpl implements AddtionExamination{@Overridepublic void doAddtionalExamination() {System.out.println("do additional questions as possible as you can.");} } 對以上代碼的分析(Analysis):
A1)這個切面與以往切面不同的是:它并沒有前置,后置等通知,而是通過 @DeclareParents注解將?AddtionExamination? 接口引入到?CollegeEntraceExamination bean中; A2)@DeclareParents注解由3個部分組成:(干貨——@DeclareParents注解的作用) part1)value屬性:指定了哪種類型的bean 要引入該接口; part2)defaultImpl:指定了為引入功能提供實現的類; part3)@DeclareParents注解所標注的靜態屬性:指明了要引入的接口; A3)和其它切面一樣,需要在spring 應用中將 AdditionExaminationIntroducer 聲明為 一個 bean; <bean class="com.spring.chapter4.AdditionExaminationIntroducer" /> spring 的自動代理機制將會獲取到它的聲明,但 spring 發現一個bean使用 @Aspect注解時,spring就會創建一個代理,然后將調用委托給被代理bean 或被引入的實現,這取決于調用的方法屬于被代理的bean 還是屬于被引入的接口;(干貨——這解釋了為什么一個spring bean的實現被拆分到了多個類中的問題)
對上圖的分析(Analysis):我們看到,即使CollegeEntraceExamination 并沒有實現?AddtionExamination接口,但是通過創建新切面為前者添加了新方法,CollegeEntraceExamination?就可以調用了doAddtionalExamination()方法了;
4)面向注解的切面聲明有一個明顯的劣勢:你必須能夠為通知類添加注解。為了做到這一點,必須要有源碼;如果沒有源碼,或不想將 AspectJ 注解放到你的代碼中,可以使用 spring XML 配置文件中聲明切面;(干貨——面向注解的切面聲明有一個明顯的劣勢)
【4】在XML 中聲明切面 1)之前有這樣一個rule:基于注解的bean裝配要優于基于JavaConfig 的裝配,基于JavaConfig的裝配 要優于基于XML的配置裝配; 2)但是,如果需要聲明切面,但又不能為通知類添加注解的時候,那么就必須轉向XML 配置了; 3)spring 的aop 配置元素能夠以非侵入性的方式聲明切面
【4.1】聲明前置和后置通知 1)通過XML 將無注解的 Examinee 聲明為切面 <aop:config><aop:aspect ref="examinee"><aop:beforepointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="checkIdentity"/><aop:beforepointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="checkIdentity"/><aop:after-returningpointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="handinPaper"/><aop:after-throwingpointcut="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))"method="cancelQualification"/></aop:aspect> </aop:config> 2)使用<aop:pointcut> 定義命名切點 <aop:config><aop:aspect ref="examinee"><aop:pointcutid="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:beforepointcut-ref="chineseExamination"method="checkIdentity"/><aop:beforepointcut-ref="chineseExamination"method="checkIdentity"/><aop:after-returningpointcut-ref="chineseExamination"method="handinPaper"/><aop:after-throwingpointcut-ref="chineseExamination"method="cancelQualification"/></aop:aspect> </aop:config> 圖片t18
Attention)spring4-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXML"><aop:pointcut id="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:before pointcut-ref="chineseExamination" method="checkIdentity" /><aop:before pointcut-ref="chineseExamination" method="checkSecurity" /><aop:after-returning pointcut-ref="chineseExamination" method="handinPaper" /><aop:after-throwing pointcut-ref="chineseExamination" method="cancelQualification" /></aop:aspect></aop:config> </beans> 【4.2】在XML配置元素中聲明環繞通知 step1)attendChineseExamination()方法提供了aop環繞通知; // 考生(就是一個切面) public class ExamineeAroundXML {private String name;public ExamineeAroundXML(String name) {this.name = name;}public void attendChineseExamination(ProceedingJoinPoint jp) {try {System.out.println("AroundXML@Before: please show us your admission ticket.");System.out.println("AroundXML@Before: please accept electronic equipment inspection.");jp.proceed();System.out.println("AroundXML@AfterReturn: please hand in an examination paper.");} catch (Throwable e) {System.out.println("AroundXML@AfterThrowing: cancel the exam qualification");}} } step2)在XML 中使用 <aop:around>元素聲明環繞通知 <aop:config><aop:aspect ref="audience"><aop:pointcutid="chineseExamination"expression="execution(** com.spring.chapter4.CollegeEntraceExamination.chineseExamination(..))" /><aop:aroundpointcut-ref="chineseExamination"method="attendChineseExamination"/></aop:aspect> </aop:config> 圖片t19
【4.3】 為通知傳遞參數(在XML中將ExamineeXMLArgs 配置為參數化的切面 ) 圖片t20
@Configuration @ImportResource("classpath:com/spring/chapter4/spring4-args-config.xml") public class ExaminationConfig {@Beanpublic CollegeEntraceExamination getExamination() {return new CollegeEntraceExamination();}@Bean(name="examineeXMLArgs")public ExamineeXMLArgs getExamineeXMLArgs() {return new ExamineeXMLArgs("xiaotang");} } spring4-args-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXMLArgs"><aop:pointcut id="getExamineeNumber"expression="execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int))and args(examSiteCode)" /><aop:before pointcut-ref="getExamineeNumber" method="checkIdentity"/></aop:aspect></aop:config> </beans>
【4.4】通過XML為切面引入新功能 圖片(t21)
@Configuration @ImportResource("classpath:com/spring/chapter4/spring4-args-intro-config.xml") public class ExaminationConfig {@Beanpublic CollegeEntraceExamination getExamination() {return new CollegeEntraceExamination();}@Bean(name="examineeXMLArgs")public ExamineeXMLArgs getExamineeXMLArgs() {return new ExamineeXMLArgs("xiaotang");} } spring4-args-intro-config.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy /><aop:config><aop:aspect ref="examineeXMLArgs"><aop:pointcut id="getExamineeNumber"expression="execution(* com.spring.chapter4.CollegeEntraceExamination.getExamineeNumber(int))and args(examSiteCode)" /><aop:before pointcut-ref="getExamineeNumber" method="checkIdentity"/></aop:aspect><aop:aspect><aop:declare-parents types-matching="com.spring.chapter4.CollegeEntraceExamination+" implement-interface="com.spring.chapter4.AddtionExamination" default-impl="com.spring.chapter4.AdditionExaminationImpl"<!-- delegate-ref="additionExaminationImpl" 前提是spring容器中有additionExaminationImpl bean--> /></aop:aspect></aop:config> </beans>
總結
以上是生活随笔為你收集整理的spring(4)面向切面的Spring(AOP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html怎么用图片做背景(html怎么用
- 下一篇: Spring4.2.6+SpringMV