1.@Aspect注解
(1) @Aspect注解用于宣告一個切面類,我們可在該類中來自定義切面,早在Spring之前,AspectJ框架中就已經存在了這么一個注解,而Spring為了提供統一的注解風格,因此采用了和AspectJ框架相同的注解方式,這便是@Aspect注解的由來,換句話說,在Spring想做AOP框架之前,AspectJ AOP框架就已經很火了,而直接把AspectJ搬過來又不現實,因此,Spring想了一個折中的方案,即只使用AspectJ框架的宣告,寫法和定義方式(比如@Aspect注解),而底層由Spring自己實作,這樣,就避免了我們程式員從AspectJ AOP切換到Spring AOP后,還要再去學一套新的寫法了,也正因為如此,如果想要使用Spring AOP,就必須依賴aspectjweaver.jar包(不然誰來提供寫法和定義方式),我們可以通過maven進行匯入,如下
<!-- 添加對AspectJ框架的依賴 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<!-- 除了上面的方式外,也可以直接使用spring-aspects依賴,它里面包含了對AspectJ的依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.framework.version}</version>
</dependency>
(2) 同時還需使用@EnableAspectJAutoProxy注解來開啟Spring對于AspectJ注解的支持,如下
@Configuration
@EnableAspectJAutoProxy
public class Config {
}
如果是基于xml的配置,可通過如下標簽進行開啟
<aop:aspectj-autoproxy/>
2.自定義一個切面類
(1) 在基于注解的配置下,除了使用@Aspect注解外,還需要宣告該切面是一個bean,否則,spring在掃描程序中是會忽略掉這個類的,如下
@Aspect
@Component
public class Logger {
}
(2) 對上面的例子,基于xml配置的寫法如下
@Aspect
public class Logger {
}
<!-- xml組態檔中 -->
<beans ...>
<!-- 無論何種配置方式,不要忘了將切面類注冊為spring的一個bean -->
<bean id="logger" ></bean>
</beans>
(3) 由@Aspect注解標注的類,稱之為切面類,與普通的類一樣,都有成員方法與成員變數,不同的是,切面類還可以包含連接點,通知,引介等與AOP有關的東西
(4) 切面不能再被增強,如果想拿一個切面來增強另一個切面,是不可能的,Spring會將切面類從自動代理(auto-proxying)中排除
3.自定義一個切入點
(1) Spring AOP中的切入點目前只可能是bean中的方法,而對于一個普通類中的方法,是不可能成為切入點的,在Spring中,宣告一個切入點主要包括兩個部分:一個切入點簽名以及一個切入點運算式,如下
//如下定義了一個叫做anyExampleAMethod的切入點,這個切入點會匹配cn.example.spring.boke包下的ExampleA類中的任何方法
//其中,(1)就代表的是切入點運算式,(2)就代表的是切入點簽名,注意,這個簽名的回傳值必須是void
@Pointcut("execution(* cn.example.spring.boke.ExampleA.*(..))") //(1)
public void anyExampleAMethod() {} //(2)
(2) Spring AOP的切入點運算式中,支持如下等切入點識別符號
-
execution:最為常用,用于匹配某個包,某個類中的方法
-
within:進行型別匹配,用于匹配某個包下所有類的所有方法或某個指定類中的所有方法,如下
//指定了within的型別,這個切入點會匹配cn.example.spring.boke包下ExampleA類中的任何方法
@Pointcut("within(cn.example.spring.boke.ExampleA)")
public void withinDesignator(){}
- this:進行型別匹配,用于匹配生成的代理物件的型別是否為指定型別,如下
//此前我們提到過,Spring AOP中的底層實作分為jdk動態代理和cglib動態代理,jdk動態代理基于介面,要求目標物件必須實作某個介面,而cglib動態代理基于繼承,因此不同的實作方式下,導致Spring生成的代理物件的型別可能不同,這就是this識別符號的基礎
//首先定義一個介面
public interface Parent {
void register();
void sendEmail();
}
//讓我們的ExampleA類,實作這個介面
@Component
public class ExampleA implements Parent{
public void register() {
}
public void sendEmail() {
}
}
//設定@EnableAspectJAutoProxy注解中的proxyTargetClass屬性值為false,表示使用jdk動態代理,為true,表示使用cglib動態代理,默認值為false,不過我們這里顯式的宣告出來
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ComponentScan(basePackages = "cn.example.spring.boke")
public class Config {
}
//切面類,在其中宣告一個this識別符號,并指定型別為ExampleA
@Aspect
@Component
public class Logger {
/**
* this識別符號,進行型別匹配,用于匹配代理物件的型別是否為指定型別
*/
@Pointcut(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/this(cn.example.spring.boke.ExampleA)")
public void thisDesignator(){}
@Around(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/thisDesignator()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println(new Date() + " 開始執行...");
joinPoint.proceed();
System.out.println(new Date() + " 結束執行...");
}
}
//執行如下列印方法,可見通知未被執行,原因就是因為我們使用了jdk動態代理,Spring為我們生成的代理物件繼承自jdk中的Proxy類并實作了Parent介面,它不屬于ExampleA型別,自然而然切入點匹配失敗,我們的通知未被執行
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
ctx.getBean(Parent.class).register();
ctx.getBean(Parent.class).sendEmail();
//列印一下系統中代理物件的型別是否為ExampleA,結果為false
System.out.println(ctx.getBean(Parent.class) instanceof ExampleA);
//為了能進行匹配,我們可以將@EnableAspectJAutoProxy中的proxyTargetClass屬性設定為true,使用cglib動態代理,這時再執行上面的列印方法,通知就會被執行了,原因就是因為使用了cglib動態代理后,Spring為我們生成的代理物件是繼承自ExampleA,當然屬于ExampleA型別,因此通知會被執行
@EnableAspectJAutoProxy(proxyTargetClass = true)
-
target:進行型別匹配,用于匹配目標物件的型別是否為指定型別,跟上面的this類似
-
args:進行方法引數匹配,用于匹配方法的引數型別是否為指定型別,如下
//ExampleA中的register方法的引數為String
@Component
public class ExampleA{
public void register(String name) {
}
public void sendEmail() {
}
}
@Aspect
@Component
public class Logger {
/**
* 指定了args引數的型別為String,因此只會與ExampleA中的register方法匹配
*/
@Pointcut(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/args(java.lang.String)")
public void argsDesignator() {}
@Around(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/argsDesignator()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println(new Date() + " 開始執行...");
joinPoint.proceed();
System.out.println(new Date() + " 結束執行...");
}
}
-
@target:用于匹配目標物件的類上有沒有標注指定注解
-
@args:用于匹配方法的引數的所屬類上有沒有標注指定注解
-
@within:用于匹配某個類上有沒有標注指定注解
-
@annotation:最常用,用于匹配某個方法上有沒有標注指定注解
(3) Spring的AOP是基于代理實作的,因此,在目標物件中進行內部呼叫是不會被攔截的(即this指標會導致AOP失效問題),此外,對于jdk動態代理,只能攔截public方法,而對于cglib動態代理,會攔截public和protected方法(package-visible 方法在配置后也能被攔截)
(4) Spring AOP還提供了一個PCD bean,用于按照bean的名稱進行切入,它是Spring AOP獨有的,如下
//匹配所有beanName以A結尾的bean
@Pointcut("bean(*A)")
public void pcd() {}
4.組合切入點運算式
(1) 可以通過 &&,|| 和 !來組合切入點運算式,如下
//切入所有public方法
@Pointcut("execution(public * *(..))")
public void allPublicMethod() {}
//切入boke包下所有類中的所有方法
@Pointcut("within(cn.example.spring.boke.*)")
public void methodInBokePackage() {}
//使用 && 運算子,將上面兩個切入點運算式組合起來,即切入boke包下所有類中的所有public方法
@Pointcut("allPublicMethod() && methodInBokePackage()")
public void allPublicMethodInBokePackage() {}
5.常見切入點運算式例子
(1)在實際作業中,我們的切入點運算式的通常形式為:execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?),其中ret-type-pattern表示一個方法的回傳型別, 用 * 號可以代表任何型別; name-pattern表示方法名稱,用 * 可以進行全部或部分名稱匹配; param-pattern表示方法引數,其中用()代表無參方法,用(..)代表任何數量的引數(0個或多個),用()代表1個引數,(, String)代表有兩個引數,第一個引數可以是任何型別,而第二個引數只能是String型別; 除此之外,其他帶有 ? 的都是選填項,可不填寫
(2)常見例子
//匹配任意public方法
execution(public * *(..))
//匹配任意名稱以set開頭的方法
execution(* set*(..))
//匹配com.xyz.service包下,AccountService類下的任意方法
execution(* com.xyz.service.AccountService.*(..))
//匹配com.xyz.service包下,任意類下的任意方法
execution(* com.xyz.service.*.*(..))
//匹配com.xyz.service包及其子包下,任意類下的任意方法
execution(* com.xyz.service..*.*(..))
//匹配com.xyz.service包下,任意類下的任意方法
within(com.xyz.service.*)
//匹配com.xyz.service包及其子包下,任意類下的任意方法
within(com.xyz.service..*)
//匹配代理物件的型別為AccountService的類下的任意方法
this(com.xyz.service.AccountService)
//匹配目標物件的型別為AccountService的類下的任意方法
target(com.xyz.service.AccountService)
//匹配方法引數只有一個且引數型別為Serializable的方法,注意它與execution(* *(java.io.Serializable))的一點區別:execution這個例子只能匹配引數型別為Serializable的方法,如果說某個方法的引數型別是Serializable的子類,是不會匹配的,而下面args這個例子可以匹配引數型別為Serializable或其子類的方法
args(java.io.Serializable)
//匹配標注了@Transactional注解的目標物件中的任意方法
@target(org.springframework.transaction.annotation.Transactional)
//匹配標注了@Transactional注解的類中的任意方法
@within(org.springframework.transaction.annotation.Transactional)
//匹配標注了@Transactional注解的任意方法
@annotation(org.springframework.transaction.annotation.Transactional)
//匹配方法的引數有且只有一個且該引數的所屬類上標注了@Classified注解的任意方法
@args(com.xyz.security.Classified)
//匹配beanName為tradeService的bean中的任意方法
bean(tradeService)
//匹配所有以Service作為beanName結尾的bean中的任意方法
bean(*Service)
6.撰寫良好的pointcuts
(1)Spring將切入點識別符號分為3大類,分別為:
- Kinded:型別識別符號,如execution, get, set, call等,它們都是根據型別進行選擇,比如execution選擇的都是可執行方法這一型別,其中除了execution,其他的都是AspectJ框架提供的
- Scoping:范圍識別符號,如within;
- Contextual:背景關系識別符號,如this, target和@annotation,它們都是根據方法所處的環境(比如在哪個類中)進行選擇
Spring建議一個良好的切入點運算式應該至少包括前兩種型別(kinded和scoping,在這兩種識別符號中scoping又特別重要,因為它的匹配速度非常快,可以快速的排除掉那些不應該被處理的方法),此外在有根據背景關系環境的需求時,可以包括contextual識別符號
7.宣告一個通知
(1)在前面已經提及過通知,它是增強的邏輯,與切入點相關聯,會在切入點執行前或執行后執行,在Spring中總共分為5大類,如下
- Before Advice:使用@Before注解可定義前置通知,它會在切入點執行之前執行
@Aspect
@Component
public class Logger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void before() {
//...
}
}
- After Returning Advice:使用@AfterReturning注解可定義回傳通知,它會在切入點"正常"執行之后執行
//一個普通的bean ExampleA
@Component
public class ExampleA{
public String doSomething() {
return "finish";
}
}
//有時候,我們可能需要訪問切入點執行后的回傳值,那么我們可以使用@AfterReturning注解中的returning屬性來指定回傳值的名稱,然后再給這個切面方法添加一個形參,這個形參型別即為切入點執行后的回傳值型別(或其父型別,但不能完全不一致,否則切面會切入失敗),形參名要與剛剛設定過的returning屬性值一致,如下例
@Aspect
@Component
public class Logger {
@AfterReturning(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))", returning = "returnVal")
public void afterReturning(Object returnVal) {
System.out.println(new Date() + " 開始執行...");
System.out.println(returnVal);
System.out.println(new Date() + " 結束執行...");
}
}
- After Throwing Advice:使用@AfterThrowing注解可定義例外通知,它會在切入點觸發例外之后執行
//同樣,我們有時候也期望訪問切入點執行程序中拋出的例外,與回傳通知一致,例子如下
@Aspect
@Component
public class Logger {
@AfterThrowing(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))", throwing = "throwable")
public void afterReturning(Throwable throwable) {
System.out.println(new Date() + " 開始執行...");
System.out.println(throwable);
System.out.println(new Date() + " 結束執行...");
}
}
- After (Finally) Advice:使用@After注解可定義后置通知,它會在切入點無論以何種方式執行(正常或例外)后執行,常用于釋放資源等目的,類似于try-catch陳述句中的finally塊,它與@AfterReturning的區別是,@AfterReturning只適用于切入點正常回傳
@Aspect
@Component
public class Logger {
@After(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void afterReturning() {
//...
}
}
- Around advice:使用@After注解可定義環繞通知,它既可以在切入點之前執行通知,又可以在切入點之后執行,甚至可以不用執行切入點,是最為靈活強大的通知
@Aspect
@Component
public class Logger {
//環繞通知方法可不宣告形參,但如果要宣告形參,第一個形參的型別必須是ProceedingJoinPoint型別,對ProceedingJoinPoint呼叫proceed方法后會導致切入點真正的執行,此外,proceed方法還有一個多載方法,我們可以對它傳遞一個Object[],那么當切入點執行時會以這個陣列中的值作為方法引數值來執行
//我們可以呼叫一次,多次或根本不呼叫proceed方法
@Around(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void afterReturning(ProceedingJoinPoint joinPoint) {
Object returnVal = null;
try {
//...
returnVal = joinPoint.proceed();
//...
} catch (Throwable e) {
//...
e.printStackTrace();
}
return returnVal;
}
}
8.切入點資訊獲取
(1)有時候,我們期望獲取到切入點相關資訊,比如它的簽名,形參等資訊,Spring為我們提供了JoinPoint型別,用于獲取相關資訊,在前面的環繞通知的例子中,我們就已經使用了JoinPoint的子型別ProceedingJoinPoint,它添加了proceed方法,來顯式的呼叫執行切入點
@Aspect
@Component
public class Logger {
//除了下面的例子外,使用JoinPoint,還可以獲取到切入點的其他一些資訊,可參考api檔案
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void before(JoinPoint joinPoint) {
System.out.println("被攔截的類:" + joinPoint.getTarget().getClass().getName());
System.out.println("被攔截的方法:" + ((MethodSignature) joinPoint.getSignature()).getMethod().getName());
System.out.println("被攔截的方法引數:" + Arrays.toString(joinPoint.getArgs()));
}
}
9.通知執行順序
(1)不同切面類中的通知,在默認情況下,按照所在切面類名的字典序排序,若其排序越高則優先級也就越高,如下
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "cn.example.spring.boke")
public class Config { }
@Component
public class ExampleA{
public void doSomething() {
System.out.println("doSomething...");
}
}
//宣告兩個切面類TimerLogger和OperationLogger
@Aspect
@Component
public class TimerLogger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void a() {
System.out.println("timer...");
}
}
@Aspect
@Component
public class OperationLogger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void a() {
System.out.println("operation...");
}
}
//啟動容器,觀察列印結果
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
ctx.getBean(ExampleA.class).doSomething();
//列印結果如下,OperationLogger中的前置通知先執行,TimerLogger中的前置通知后執行,就是因為O的字典序列大于T,因此OperationLogger中的通知的優先級高于TimerLogger中的,而對于前置通知而言,優先級越高的越先執行,對于后置通知,優先級越高的越后執行
operation...
timer...
doSomething...
//我們可以將TimerLogger改為ATimerLogger,這樣的話它里面的前置通知就會先執行了
@Aspect
@Component
public class ATimerLogger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void a() {
System.out.println("timer...");
}
}
(2)我們可以對切面類實作Ordered介面或添加@Order注解來顯示的指定優先級,其中指定的值越小,優先級越高
//此時TimerLogger的優先級高于OperationLogger
@Aspect
@Component
@Order(1)
public class TimerLogger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void a() {
System.out.println("timer...");
}
}
@Aspect
@Component
@Order(2)
public class OperationLogger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void a() {
System.out.println("operation...");
}
}
(3)對于同個切面類中的相同型別的通知,其優先級只與通知方法名字典序的排序有關,排序越高,優先級越高,如下
//Logger切面類中定義了兩個前置通知為aPrint和bPrint
@Aspect
@Component
public class Logger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void aPrint() {
System.out.println("a");
}
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
public void bPrint() {
System.out.println("b");
}
}
//啟動容器,可見aPrint先于bPrint,這就是因為a的字典序高于b
a
b
doSomething...
//將aPrint改為caPrint,這時bPrint會先執行,因為此時它的字典序高
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
publicvoid caPrint() {
System.out.println("a");
}
//此外使用@Order注解,無法改變優先級,因為此時顯式指定優先級的策略已經失效了,如下面這個例子還是按照之前默認的優先級進行執行
@Aspect
@Component
public class Logger {
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
@Order(Ordered.LOWEST_PRECEDENCE)
public void aPrint() {
System.out.println("a");
}
@Before(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/execution(* cn.example.spring.boke.ExampleA.*(..))")
@Order(Ordered.HIGHEST_PRECEDENCE)
public void bPrint() {
System.out.println("b");
}
}
10.Introductions(引介)
(1)引介能夠使指定的物件實作某些介面,并提供對這些介面的實作,以達到向物件中動態添加它所沒有方法的目的,例子如下
//我們希望向ExampleA類中增加某些新的方法
@Component
public class ExampleA{ }
//宣告一個介面,這個介面里的方法即為我們希望增加的新的方法
public interface Extention {
void doSomething();
}
//新方法的具體實作
public class ExtentionImpl implements Extention{
@Override
public void doSomething() {
System.out.println("doSomething...");
}
}
//定義一個切面
@Component
@Aspect
public class MyAspect {
//使用@DeclarePrents注解,宣告被攔截的類有一個新的父型別,其中value指定攔截哪些類,在下面這個例子中指定攔截cn.example.spring.boke包下的所有類,同時指定它們的父型別均為Extention,具體的實作為ExtentionImpl
@DeclareParents(value = "https://www.cnblogs.com/shame11/archive/2023/04/17/cn.example.spring.boke.*", defaultImpl = ExtentionImpl.class)
public Extention extention;
}
//開啟AOP
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "cn.example.spring.boke")
public class Config { }
//啟動容器,從容器中獲取到exampleA并將其強制轉換為Extention,這樣我們就能使用向ExampleA中新添加的方法了
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
Extention exampleA = (Extention)ctx.getBean("exampleA");
exampleA.doSomething();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/550305.html
標籤:其他
上一篇:Gin框架