欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

聊聊Spring AOP @Before @Around @After等advice的執(zhí)行順序

 更新時間:2021年02月19日 12:01:31   作者:rainbow702  
這篇文章主要介紹了聊聊Spring AOP @Before @Around @After等advice的執(zhí)行順序,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

用過spring框架進(jìn)行開發(fā)的人,多多少少會使用過它的AOP功能,都知道有@Before、@Around和@After等advice。

最近,為了實現(xiàn)項目中的輸出日志和權(quán)限控制這兩個需求,我也使用到了AOP功能。

我使用到了@Before、@Around這兩個advice。但在,使用過程中,卻對它們的執(zhí)行順序并不清楚。

為了弄清楚在不同情況下,這些advice到底是以怎么樣的一個順序進(jìn)行執(zhí)行的,我作了個測試,在此將其記錄下來,以供以后查看。

前提

對于AOP相關(guān)類(aspect、pointcut等)的概念,本文不作說明。

對于如何讓spring框架掃描到AOP,本文也不作說明。

情況一: 一個方法只被一個Aspect類攔截

當(dāng)一個方法只被一個Aspect攔截時,這個Aspect中的不同advice是按照怎樣的順序進(jìn)行執(zhí)行的呢?請看:

添加 PointCut類

該pointcut用來攔截test包下的所有類中的所有方法。

package test;
import org.aspectj.lang.annotation.Pointcut;
public class PointCuts {
 @Pointcut(value = "within(test.*)")
 public void aopDemo() {
 }
}

添加Aspect類

該類中的advice將會用到上面的pointcut,使用方法請看各個advice的value屬性。

package test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aspect1 {
 @Before(value = "test.PointCuts.aopDemo()")
 public void before(JoinPoint joinPoint) {
  System.out.println("[Aspect1] before advise");
 }
 @Around(value = "test.PointCuts.aopDemo()")
 public void around(ProceedingJoinPoint pjp) throws Throwable{
  System.out.println("[Aspect1] around advise 1");
  pjp.proceed();
  System.out.println("[Aspect1] around advise2");
 }
 @AfterReturning(value = "test.PointCuts.aopDemo()")
 public void afterReturning(JoinPoint joinPoint) {
  System.out.println("[Aspect1] afterReturning advise");
 }
 @AfterThrowing(value = "test.PointCuts.aopDemo()")
 public void afterThrowing(JoinPoint joinPoint) {
  System.out.println("[Aspect1] afterThrowing advise");
 }
 @After(value = "test.PointCuts.aopDemo()")
 public void after(JoinPoint joinPoint) {
  System.out.println("[Aspect1] after advise");
 }
}

添加測試用Controller

添加一個用于測試的controller,這個controller中只有一個方法,但是它會根據(jù)參數(shù)值的不同,會作出不同的處理:一種是正常返回一個對象,一種是拋出異常(因為我們要測試@AfterThrowing這個advice)

package test;
import test.exception.TestException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/aop")
public class AopTestController {
 @ResponseStatus(HttpStatus.OK)
 @RequestMapping(value = "/test", method = RequestMethod.GET)
 public Result test(@RequestParam boolean throwException) {
  // case 1
  if (throwException) {
   System.out.println("throw an exception");
   throw new TestException("mock a server exception");
  }
  // case 2
  System.out.println("test OK");
  return new Result() {{
   this.setId(111);
   this.setName("mock a Result");
  }};
 }
 public static class Result {
  private int id;
  private String name;
  public int getId() {
   return id;
  }
  public void setId(int id) {
   this.id = id;
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
 }
}

測試 正常情況

在瀏覽器直接輸入以下的URL,回車:

http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=false

我們會看到輸出的結(jié)果是:

[Aspect1] around advise 1
[Aspect1] before advise
test OK
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise

測試 異常情況

在瀏覽器中直接輸入以下的URL,回車:

http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=true

我們會看到輸出的結(jié)果是:

[Aspect1] around advise 1
[Aspect1] before advise
throw an exception
[Aspect1] after advise
[Aspect1] afterThrowing advise

結(jié)論

在一個方法只被一個aspect類攔截時,aspect類內(nèi)部的 advice 將按照以下的順序進(jìn)行執(zhí)行:

正常情況:

異常情況:

情況二: 同一個方法被多個Aspect類攔截

此處舉例為被兩個aspect類攔截。

有些情況下,對于兩個不同的aspect類,不管它們的advice使用的是同一個pointcut,還是不同的pointcut,都有可能導(dǎo)致同一個方法被多個aspect類攔截。那么,在這種情況下,這多個Aspect類中的advice又是按照怎樣的順序進(jìn)行執(zhí)行的呢?請看:

pointcut類保持不變

添加一個新的aspect類

package test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aspect2 {
 @Before(value = "test.PointCuts.aopDemo()")
 public void before(JoinPoint joinPoint) {
  System.out.println("[Aspect2] before advise");
 }
 @Around(value = "test.PointCuts.aopDemo()")
 public void around(ProceedingJoinPoint pjp) throws Throwable{
  System.out.println("[Aspect2] around advise 1");
  pjp.proceed();
  System.out.println("[Aspect2] around advise2");
 }
 @AfterReturning(value = "test.PointCuts.aopDemo()")
 public void afterReturning(JoinPoint joinPoint) {
  System.out.println("[Aspect2] afterReturning advise");
 }
 @AfterThrowing(value = "test.PointCuts.aopDemo()")
 public void afterThrowing(JoinPoint joinPoint) {
  System.out.println("[Aspect2] afterThrowing advise");
 }
 @After(value = "test.PointCuts.aopDemo()")
 public void after(JoinPoint joinPoint) {
  System.out.println("[Aspect2] after advise");
 }
}

測試用Controller也不變

還是使用上面的那個Controller。但是現(xiàn)在 aspect1 和 aspect2 都會攔截該controller中的方法。

下面繼續(xù)進(jìn)行測試!

測試 正常情況

在瀏覽器直接輸入以下的URL,回車:

http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=false

我們會看到輸出的結(jié)果是:

[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] before advise
test OK
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise

但是這個時候,我不能下定論說 aspect2 肯定就比 aspect1 先執(zhí)行。

不信?你把服務(wù)務(wù)器重新啟動一下,再試試,說不定你就會看到如下的執(zhí)行結(jié)果:

[Aspect1] around advise 1
[Aspect1] before advise
[Aspect2] around advise 1
[Aspect2] before advise
test OK
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise

也就是說,這種情況下, aspect1 和 aspect2 的執(zhí)行順序是未知的。那怎么解決呢?不急,下面會給出解決方案。

測試 異常情況

在瀏覽器中直接輸入以下的URL,回車:

http://192.168.142.8:7070/aoptest/v1/aop/test?throwException=true

我們會看到輸出的結(jié)果是:

[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] before advise
throw an exception
[Aspect1] after advise
[Aspect1] afterThrowing advise
[Aspect2] after advise
[Aspect2] afterThrowing advise

同樣地,如果把服務(wù)器重啟,然后再測試的話,就可能會看到如下的結(jié)果:

[Aspect1] around advise 1
[Aspect1] before advise
[Aspect2] around advise 1
[Aspect2] before advise
throw an exception
[Aspect2] after advise
[Aspect2] afterThrowing advise
[Aspect1] after advise
[Aspect1] afterThrowing advise

也就是說,同樣地,異常情況下, aspect1 和 aspect2 的執(zhí)行順序也是未定的。

那么在 情況二 下,如何指定每個 aspect 的執(zhí)行順序呢?

方法有兩種:

實現(xiàn)org.springframework.core.Ordered接口,實現(xiàn)它的getOrder()方法

給aspect添加@Order注解,該注解全稱為:org.springframework.core.annotation.Order

不管采用上面的哪種方法,都是值越小的 aspect 越先執(zhí)行。

比如,我們?yōu)?apsect1 和 aspect2 分別添加 @Order 注解,如下:

@Order(5)
@Component
@Aspect
public class Aspect1 {
 // ...
}
@Order(6)
@Component
@Aspect
public class Aspect2 {
 // ...
}

這樣修改之后,可保證不管在任何情況下, aspect1 中的 advice 總是比 aspect2 中的 advice 先執(zhí)行。

如下圖所示:

注意點(diǎn)

如果在同一個 aspect 類中,針對同一個 pointcut,定義了兩個相同的 advice(比如,定義了兩個 @Before),那么這兩個 advice 的執(zhí)行順序是無法確定的,哪怕你給這兩個 advice 添加了 @Order 這個注解,也不行。這點(diǎn)切記。

對于@Around這個advice,不管它有沒有返回值,但是必須要方法內(nèi)部,調(diào)用一下 pjp.proceed();否則,Controller 中的接口將沒有機(jī)會被執(zhí)行,從而也導(dǎo)致了 @Before這個advice不會被觸發(fā)。

比如,我們假設(shè)正常情況下,執(zhí)行順序為”aspect2 -> apsect1 -> controller”,如果,我們把 aspect1中的@Around中的 pjp.proceed();給刪掉,那么,我們看到的輸出結(jié)果將是:

[Aspect2] around advise 1
[Aspect2] before advise
[Aspect1] around advise 1
[Aspect1] around advise2
[Aspect1] after advise
[Aspect1] afterReturning advise
[Aspect2] around advise2
[Aspect2] after advise
[Aspect2] afterReturning advise

從結(jié)果可以發(fā)現(xiàn), Controller 中的 接口 未被執(zhí)行,aspect1 中的 @Before advice 也未被執(zhí)行。

參考資料

Spring 4.3.2.RELEASE 官方資料:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/

其中,AOP的執(zhí)行順序章節(jié)為:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop-ataspectj-advice-ordering

Advice ordering

What happens when multiple pieces of advice all want to run at the same join point?

Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution.

The highest precedence advice runs first "on the way in" (so given two pieces of before advice, the one with highest precedence runs first).

"On the way out" from a join point, the highest precedence advice runs last (so given two pieces of after advice, the one with the highest precedence will run second).

When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise the order of execution is undefined.

You can control the order of execution by specifying precedence.

This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation.

Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.

When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order via reflection for javac-compiled classes).

Consider collapsing such advice methods into one advice method per join point in each aspect class, or refactor the pieces of advice into separate aspect classes - which can be ordered at the aspect level.

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • Java中對象快速復(fù)制的幾種方式詳解

    Java中對象快速復(fù)制的幾種方式詳解

    這篇文章主要介紹了Java中對象快速復(fù)制的幾種方式詳解,對象的克隆是指創(chuàng)建一個新的對象,且新的對象的狀態(tài)與原始對象的狀態(tài)相同,當(dāng)對克隆的新對象進(jìn)行修改時,不會影響原始對象的狀態(tài),需要的朋友可以參考下
    2023-08-08
  • MySQL中關(guān)鍵字UNION和UNION ALL的區(qū)別

    MySQL中關(guān)鍵字UNION和UNION ALL的區(qū)別

    本文主要介紹了MySQL中關(guān)鍵字UNION和UNION ALL的區(qū)別,深入探討UNION和UNION ALL的定義、用法、主要區(qū)別,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06
  • springboot整合mybatis-plus基于注解實現(xiàn)一對一(一對多)查詢功能

    springboot整合mybatis-plus基于注解實現(xiàn)一對一(一對多)查詢功能

    這篇文章主要介紹了springboot整合mybatis-plus基于純注解實現(xiàn)一對一(一對多)查詢功能,因為本人采用的是spring-boot進(jìn)行開發(fā),本身springboot就提倡采用不用配置自動配置的方式,所以真心希望mybatis(不是mybatis-plus)這點(diǎn)需要繼續(xù)努力
    2021-09-09
  • 自己動手在Spring-Boot上加強(qiáng)國際化功能的示例

    自己動手在Spring-Boot上加強(qiáng)國際化功能的示例

    這篇文章主要介紹了自己動手在Spring-Boot上加強(qiáng)國際化功能的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • Spring AOP面向切面編程實現(xiàn)原理方法詳解

    Spring AOP面向切面編程實現(xiàn)原理方法詳解

    這篇文章主要介紹了Spring AOP面向切面編程實現(xiàn)原理方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • 解決java.sql.SQLException:The?server?time?zone?value?'?D1ú±ê×?ê±??'?is?unrecognized問題

    解決java.sql.SQLException:The?server?time?zone?value?&apo

    這篇文章主要介紹了解決java.sql.SQLException:The?server?time?zone?value?'?D1ú±ê×?ê±??'?is?unrecognized問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • 利用Maven添加工程版本信息及時間戳

    利用Maven添加工程版本信息及時間戳

    這篇文章主要介紹了利用Maven添加工程版本信息及時間戳方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot實現(xiàn)文件在線預(yù)覽功能的全過程

    SpringBoot實現(xiàn)文件在線預(yù)覽功能的全過程

    我們開發(fā)業(yè)務(wù)系統(tǒng)的時候,經(jīng)常有那種文檔文件在線預(yù)覽的需求,下面這篇文章主要給大家介紹了關(guān)于SpringBoot實現(xiàn)文件在線預(yù)覽功能的相關(guān)資料,需要的朋友可以參考下
    2021-11-11
  • Java多線程的用法詳解

    Java多線程的用法詳解

    本篇文章介紹了,在Java中多線程的用法詳解。需要的朋友參考下
    2013-04-04
  • springboot3生成本地文件url的實現(xiàn)示例

    springboot3生成本地文件url的實現(xiàn)示例

    本文主要介紹了springboot3生成本地文件url的實現(xiàn)示例,從而提供一種高效的文件管理方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01

最新評論