Spring註解驅動開發 AOP面向切面

2021-08-20 10:54:22 字數 2744 閱讀 6891

aop:在程式執行期間,動態的將某段**切入到指定方法執行時的指定時機執行,其實就是動態**。

spring提供了對aop很好的支援,使用時需要匯入spring-aspects包。

業務邏輯類:要求在業務方法執行時列印日誌

public class mathcalculator 

}

切面類:類上需要註解@aspect,切面類中的方法需要動態感知業務方法的執**況

@aspect 

public class aopaspect

@after("public int com.bdm.aop.mathcalculator.*(int, int)")

public void logend()

@afterreturning("public int com.bdm.aop.mathcalculator.*(..)")

public void logreturn()

@afterthrowing("public int com.bdm.aop.mathcalculator.div(..)")

public void logexception()

}

切面類中的方法也稱為通知方法:

前置通知(@before):在目標方法執行之前執行

後置通知(@after):在目標方法執行之後執行,即使出現異常也會執行

返回通知(@afterreturning):在目標方法正常返回之後執行

異常通知(@afterthrowing):在目標方法執行出現異常之後執行

環繞通知(@around):動態**,手動推進目標方法的執行

在使用這些註解的時候必須配合切入點表示式,來指明在哪些方法執行之前、之後、返回時、異常時執行,在寫切入點表示式時可以使用萬用字元*表示所有方法或者類,入參可以使用..表示所有引數型別

如果切入點表示式一樣的話,則可以使用乙個方法抽取切入點表示式,注意該方法的名稱可以任意,而且方法體內無需寫任何內容,只需要使用@pointcut註解並將切入點表示式標明即可:

@aspect public class aopaspect 

@before("pointcut()")

public void logstart()

@after("com.bdm.aop.aopaspect.pointcut()")

public void logend()

@afterreturning("pointcut()")

public void logreturn()

@afterthrowing("com.bdm.aop.aopaspect.pointcut()")

public void logexception()

}

本類中使用時可直接寫方法名,其他類也想使用此切入點表示式時則需要使用該方法的全類名

容器會將標註有@aspect註解的類認為是切面類

使用spring的切面需要開啟spring的切面自動**,只需要在配置類中加註解@enableaspectjautoproxy,spring中有很多@enable***註解,用來開啟一些功能

@configuration

@enableaspectjautoproxy

public class aopconfig

@bean

public aopaspect aspect()

}

配置bean怎麼區分哪個bean是切面類呢,它會看哪個類上有@aspect註解,另外切面方法的執行僅對spring容器中的bean起作用,對於我們自己new出來的物件是不起作用的,原因也很簡單,我們自己建立的bean並沒有被spring管理,也就沒有為其設定切面方法等。

通過joinpoint物件獲取呼叫目標方法時的資訊,比如方法名、引數等,使用returning指定用通知方法的哪個入參接收返回值,使用throwing指定用哪個入參接收異常,另外如果使用joinpoint,則必須將其放在切面方法入參的第乙個位置,否則會報錯:

@aspect

public class aopaspect

@before("pointcut()")

public void logstart(joinpoint point)

@after("com.bdm.aop.aopaspect.pointcut()")

public void logend(joinpoint point)

@afterreturning(value="pointcut()",returning="obj")

public void logreturn(joinpoint point,object obj)

@afterthrowing(value="com.bdm.aop.aopaspect.pointcut()",throwing="exception")

public void logexception(exception exception)

}

總結:

1、將切面類(@aspect標註的類)納入到配置類中,業務類物件也必須由spring容器建立

2、切面方法加上通知註解(@before、@after、@afterreturning、@afterthrowing、@round),並寫上切入點表示式,告訴切面方法在執行哪些方法前、後等時點執行這些切面方法

3、啟用基於註解的aop模式:配置類上加註解@enableaspectjautoproxy

Spring註解驅動開發 AOP原理簡述

要有aop功能必須要加 enableaspectjautoproxy註解 enableaspectjautoproxy註解會給容器中新增乙個後置處理器,這個後置處理器會在bean的建立前後被呼叫,bean建立完成後,會檢查這個bean是否需要增強,如果需要增強,就會通過動態 技術生成乙個 物件,物件...

Spring註解驅動開發(三) AOP使用

本篇主要講解spring aop的使用。如需檢視實現原理,移步 spring原始碼解析 三 aop實現原理 dependency groupid org.springframework groupid artifactid spring aspects artifactid version 4.3....

Spring註解驅動 註解實現AOP切面程式設計

需求 在指定包下的所有類中的有方法都加上前置和後置通知。1.aop類,使用的註解 aspect表示當前的類為aop類 aspect public class logaop after execution service.public void doafter bean public logaop l...