1. 程式人生 > >【線上排查實戰】AOP切面執行順序你真的瞭解嗎

【線上排查實戰】AOP切面執行順序你真的瞭解嗎

# 前言 > 忙,是我這個月的主旋律,也是我頻繁鴿文章的介面————蠻三刀把刀 公司這兩個月啟動了全新的專案,專案排期滿滿當當,不過該學習還是要學習。這不,給公司搭專案的時候,踩到了一個Spring AOP的坑。 本文內容重點: - 問題描述 - Spring AOP執行順序 - 探究順序錯誤的真相 - 程式碼驗證 - 結論 > **本文閱讀大概需要:3分鐘** > > 碼字不易,求個關注,歡迎關注我的個人原創公眾號:後端技術漫談(二維碼見文章底部) # 問題描述 公司新專案需要搭建一個新的前後分離HTTP服務,我選擇了目前比較熟悉的SpringBoot Web來快速搭建一個可用的系統。 魯迅說過,**不要隨便升級已經穩定使用的版本**。我偏不信這個邪,仗著自己用了這麼久Spring,怎麼能不衝呢。不說了,直接引入了最新的SprinBoot 2.3.4.RELEASE版本,開始給專案搭架子。 起初,大多數的元件引入都一切順利,本以為就要大功告成了,沒想到在搭建**日誌切面**時栽了跟頭。 > 作為一個介面服務,為了方便查詢介面呼叫情況和定位問題,一般都會將請求日誌打印出來,而Spring的AOP作為切面支援,完美的切合了日誌記錄的需求。 之前的專案中,執行正確的切面日誌記錄效果如下圖: ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777844392-image.png) 可以看到圖內的一次方法呼叫,會輸出請求url,出入參,以及請求IP等等,之前為了好看,還加入了分割線。 我把這個實現類放入新專案中,執行出來卻是這樣的: ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777853908-image.png) 我揉了揉眼睛,仔細看了看複製過來的老程式碼,精簡版如下: ``` /** * 在切點之前織入 * @param joinPoint * @throws Throwable */ @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 開始列印請求日誌 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 初始化traceId initTraceId(request); // 列印請求相關引數 LOGGER.info("========================================== Start =========================================="); // 列印請求 url LOGGER.info("URL : {}", request.getRequestURL().toString()); // 列印 Http method LOGGER.info("HTTP Method : {}", request.getMethod()); // 列印呼叫 controller 的全路徑以及執行方法 LOGGER.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); // 列印請求的 IP LOGGER.info("IP : {}", IPAddressUtil.getIpAdrress(request)); // 列印請求入參 LOGGER.info("Request Args : {}", joinPoint.getArgs()); } /** * 在切點之後織入 * @throws Throwable */ @After("webLog()") public void doAfter() throws Throwable { LOGGER.info("=========================================== End ==========================================="); } /** * 環繞 * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("webLog()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = proceedingJoinPoint.proceed(); // 打印出參 LOGGER.info("Response Args : {}", result); // 執行耗時 LOGGER.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); return result; } ``` 程式碼感覺完全沒有問題,難道新版本的SpringBoot出Bug了。 顯然,成熟的框架不會在這種大方向上犯錯誤,那會不會是新版本的SpringBoot把@After和@Around的順序反過來了? 其實事情也沒有那麼簡單。 # Spring AOP執行順序 我們先來回顧下Spring AOP執行順序。 我們在網上查詢關於SpringAop執行順序的的資料,大多數時候,你會查到如下的答案: ## 正常情況 ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777864590-image.png) ## 異常情況 ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777870756-image.png) ## 多個切面的情況 ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777876850-image.png) 所以@Around理應在@After之前,但是在SprinBoot 2.3.4.RELEASE版本中,@Around切切實實執行在了@After之後。 **當我嘗試切換回2.2.5.RELEASE版本後,執行順序又回到了@Around-->@After** # 探究順序錯誤的真相 既然知道了是SpringBoot版本升級導致的問題(或者說順序變化),那麼就要來看看究竟是哪個庫對AOP執行的順序進行了變動,畢竟,SpringBoot只是“形”,真正的核心在Spring。 我們開啟pom.xml檔案,使用外掛檢視spring-aop的版本,發現SpringBoot 2.3.4.RELEASE 版本使用的AOP是spring-aop-5.2.9.RELEASE。 而2.2.5.RELEASE對應的是spring-aop-5.2.4.RELEASE 於是我去官網搜尋文件,不得不說Spring由於過於龐大,官網的文件已經到了冗雜的地步,不過最終還是找到了: https://docs.spring.io/spring-framework/docs/5.2.9.RELEASE/spring-framework-reference/core.html#aop-ataspectj-advice-ordering ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777930052-image.png) > As of Spring Framework 5.2.7, advice methods defined in the same @Aspect class that need to run at the same join point are assigned precedence based on their advice type in the following order, from highest to lowest precedence: @Around, @Before, @After, @AfterReturning, @AfterThrowing. 我粗淺的翻譯一下重點: **從Spring5.2.7開始,在相同@Aspect類中,通知方法將根據其型別按照從高到低的優先順序進行執行:@Around,@Before ,@After,@AfterReturning,@AfterThrowing。** 這樣看其實對比不明顯,我們再回到老版本,也就是2.2.5.RELEASE對應的spring-aop-5.2.4.RELEASE,當時的文件是這麼寫的: > 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). **簡單翻譯:在相同@Aspect類中Spring AOP遵循與AspectJ相同的優先順序規則來確定advice執行的順序。** 再挖深一點,那麼AspectJ的優先順序規則是什麼樣的? 我找了AspectJ的文件: https://www.eclipse.org/aspectj/doc/next/progguide/semantics-advice.html ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777941209-image.png) > At a particular join point, advice is ordered by precedence. > > A piece of around advice controls whether advice of lower precedence will run by calling proceed. The call to proceed will run the advice with next precedence, or the computation under the join point if there is no further advice. > > A piece of before advice can prevent advice of lower precedence from running by throwing an exception. If it returns normally, however, then the advice of the next precedence, or the computation under the join pint if there is no further advice, will run. > > Running after returning advice will run the advice of next precedence, or the computation under the join point if there is no further advice. Then, if that computation returned normally, the body of the advice will run. > > Running after throwing advice will run the advice of next precedence, or the computation under the join point if there is no further advice. Then, if that computation threw an exception of an appropriate type, the body of the advice will run. > > Running after advice will run the advice of next precedence, or the computation under the join point if there is no further advice. Then the body of the advice will run. 大夥又要說了,哎呀太長不看!簡短地說,Aspectj的規則就是上面我們能夠在網上查閱到的順序圖展示的那樣,依舊是老的順序。 # 程式碼驗證 我把業務邏輯從程式碼中刪除,只驗證下這幾個advice的執行順序: ``` package com.bj58.xfbusiness.cloudstore.system.aop; import com.bj58.xfbusiness.cloudstore.utils.IPAddressUtil; import com.bj58.xfbusiness.cloudstore.utils.TraceIdUtil; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * 日誌切面 */ @Aspect @Component public class WebLogAspect { private final static Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class); /** 以 controller 包下定義的所有請求為切入點 */ @Pointcut("execution(public * com.xx.xxx.xxx.controller..*.*(..))") public void webLog() {} /** * 在切點之前織入 * @param joinPoint * @throws Throwable */ @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { LOGGER.info("-------------doBefore-------------"); } @AfterReturning("webLog()") public void afterReturning() { LOGGER.info("-------------afterReturning-------------"); } @AfterThrowing("webLog()") public void afterThrowing() { LOGGER.info("-------------afterThrowing-------------"); } /** * 在切點之後織入 * @throws Throwable */ @After("webLog()") public void doAfter() throws Throwable { LOGGER.info("-------------doAfter-------------"); } /** * 環繞 * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("webLog()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { long startTime = System.currentTimeMillis(); LOGGER.info("-------------doAround before proceed-------------"); Object result = proceedingJoinPoint.proceed(); LOGGER.info("-------------doAround after proceed-------------"); return result; } ``` 我們將版本改為,結果如圖: ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777908003-image.png) 我們將版本改為,結果如圖: ![](https://gitee.com/qqxx6661/markdown-pic/raw/master/2020-10-16/1602777899090-image.png) # 結論 經過上面的資料文件查閱,**我能給出的結論是**: **從Spring5.2.7開始,Spring AOP不再嚴格按照AspectJ定義的規則來執行advice,而是根據其型別按照從高到低的優先順序進行執行:@Around,@Before ,@After,@AfterReturning,@AfterThrowing。** 這次的研究思考十分倉促,如果結論有誤請大家踴躍指正,也歡迎大家自己嘗試,畢竟口說無憑,實驗室檢驗真理的唯一標準! # 參考 https://www.cnblogs.com/dennyLee2025/p/13724981.html https://segmentfault.com/a/1190000011283029 ## 關注我 我是一名後端開發工程師。主要關注後端開發,資料安全,邊緣計算等方向,歡迎交流。 ### 各大平臺都可以找到我 - **微信公眾號:後端技術漫談** - **Github:[@qqxx6661](https://github.com/qqxx6661)** - CSDN:[@蠻三刀把刀](http://blog.csdn.net/qqxx6661) - 知乎:[@後端技術漫談](https://www.zhihu.com/people/yang-zhen-dong-1/) - 掘金:[@蠻三刀把刀](https://juejin.im/user/5b48015ce51d45191462ba55) - 騰訊雲+社群:[@後端技術漫談](https://cloud.tencent.com/developer/user/1706868) ### 原創文章主要內容 - 後端開發實戰 - Java面試知識 - 設計模式/資料結構/演算法題解 - 讀書筆記/逸聞趣事/程式人生 ### 個人公眾號:後端技術漫談 ![個人公眾號:後端技術漫談](http://ww1.sinaimg.cn/large/8de6a3d3gy1genhmip8aqg20go0gojz5.gif) **如果文章對你有幫助,不妨點贊,收藏