面試官:Spring 註解 @After,@Around,@Before 的執行順序是?
AOP中有@Before
,@After
,@Around
,@AfterRunning
註解等等。
首先上下自己的程式碼,定義了切點的定義
``` @Aspect @Component public class LogApsect {
private static final Logger logger = LoggerFactory.getLogger(LogApsect.class);
ThreadLocal<Long> startTime = new ThreadLocal<>();
// 第一個*代表返回型別不限
// 第二個*代表所有類
// 第三個*代表所有方法
// (..) 代表引數不限
@Pointcut("execution(public * com.lmx.blog.controller.*.*(..))")
@Order(2)
public void pointCut(){};
@Pointcut("@annotation(com.lmx.blog.annotation.RedisCache)")
@Order(1) // Order 代表優先順序,數字越小優先順序越高
public void annoationPoint(){};
@Before(value = "annoationPoint() || pointCut()")
public void before(JoinPoint joinPoint){
System.out.println("方法執行前執行......before");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("<=====================================================");
logger.info("請求來源: =》" + request.getRemoteAddr());
logger.info("請求URL:" + request.getRequestURL().toString());
logger.info("請求方式:" + request.getMethod());
logger.info("響應方法:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("請求引數:" + Arrays.toString(joinPoint.getArgs()));
logger.info("------------------------------------------------------");
startTime.set(System.currentTimeMillis());
}
// 定義需要匹配的切點表示式,同時需要匹配引數
@Around("pointCut() && args(arg)")
public Response around(ProceedingJoinPoint pjp,String arg) throws Throwable{
System.out.println("name:" + arg);
System.out.println("方法環繞start...around");
String result = null;
try{
result = pjp.proceed().toString() + "aop String";
System.out.println(result);
}catch (Throwable e){
e.printStackTrace();
}
System.out.println("方法環繞end...around");
return (Response) pjp.proceed();
}
@After("within(com.lmx.blog.controller.*Controller)")
public void after(){
System.out.println("方法之後執行...after.");
}
@AfterReturning(pointcut="pointCut()",returning = "rst")
public void afterRunning(Response rst){
if(startTime.get() == null){
startTime.set(System.currentTimeMillis());
}
System.out.println("方法執行完執行...afterRunning");
logger.info("耗時(毫秒):" + (System.currentTimeMillis() - startTime.get()));
logger.info("返回資料:{}", rst);
logger.info("==========================================>");
}
@AfterThrowing("within(com.lmx.blog.controller.*Controller)")
public void afterThrowing(){
System.out.println("異常出現之後...afterThrowing");
}
} ```
推薦一個 Spring Boot 基礎教程及實戰示例: http://github.com/javastacks/spring-boot-best-practice
@Before
,@After
,@Around
註解的區別大家可以自行百度下。總之就是@Around
可以實現@Before
和@After
的功能,並且只需要在一個方法中就可以實現。
首先我們來測試一個方法用於獲取資料庫一條記錄的
@RequestMapping("/achieve")
public Response achieve(){
System.out.println("方法執行-----------");
return Response.ok(articleDetailSercice.getPrimaryKeyById(1L));
}
以下是控制檯列印的日誌
方法執行前執行......before
2018-11-23 16:31:59.795 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - <=====================================================
2018-11-23 16:31:59.795 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 請求來源: =》0:0:0:0:0:0:0:1
2018-11-23 16:31:59.795 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 請求URL:http://localhost:8888/user/achieve
2018-11-23 16:31:59.795 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 請求方式:GET
2018-11-23 16:31:59.795 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 響應方法:com.lmx.blog.controller.UserController.achieve
2018-11-23 16:31:59.796 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 請求引數:[]
2018-11-23 16:31:59.796 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - ------------------------------------------------------
方法執行-----------
2018-11-23 16:31:59.806 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - ==> Preparing: select * from article_detail where id = ?
2018-11-23 16:31:59.806 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - ==> Preparing: select * from article_detail where id = ?
2018-11-23 16:31:59.806 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - ==> Parameters: 1(Long)
2018-11-23 16:31:59.806 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - ==> Parameters: 1(Long)
2018-11-23 16:31:59.814 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - <== Total: 1
2018-11-23 16:31:59.814 [http-nio-8888-exec-9] DEBUG c.l.b.m.A.selectPrimaryKey - <== Total: 1
方法之後執行...after.
方法執行完執行...afterRunning
2018-11-23 16:31:59.824 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 耗時(毫秒):27
2018-11-23 16:31:59.824 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - 返回資料:com.lmx.blog.common.Response@8675ce5
2018-11-23 16:31:59.824 [http-nio-8888-exec-9] INFO c.l.blog.config.LogApsect - ==========================================>
可以看到,因為沒有匹配@Around
的規則,所以沒有進行環繞通知。(PS:我定義的環繞通知意思是要符合是 controller 包下的方法並且方法必須帶有引數,而上述方法沒有引數,所以只走了@before
和@after
方法,不符合@Around
的匹配邏輯)
我們再試一下另一個帶有引數的方法
@RedisCache(type = Response.class)
@RequestMapping("/sendEmail")
public Response sendEmailToAuthor(String content){
System.out.println("測試執行次數");
return Response.ok(true);
}
以下是該部分程式碼的console列印
name:第二封郵件呢
方法環繞start...around
方法執行前執行......before
2018-11-23 16:34:55.347 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - <=====================================================
2018-11-23 16:34:55.347 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求來源: =》0:0:0:0:0:0:0:1
2018-11-23 16:34:55.347 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求URL:http://localhost:8888/user/sendEmail
2018-11-23 16:34:55.348 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求方式:GET
2018-11-23 16:34:55.348 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 響應方法:com.lmx.blog.controller.UserController.sendEmailToAuthor
2018-11-23 16:34:55.348 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求引數:[第二封郵件呢]
2018-11-23 16:34:55.348 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - ------------------------------------------------------
測試執行次數
com.lmx.blog.common.Response@6d17f2fdaop String
方法環繞end...around
方法執行前執行......before
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - <=====================================================
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求來源: =》0:0:0:0:0:0:0:1
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求URL:http://localhost:8888/user/sendEmail
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求方式:GET
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 響應方法:com.lmx.blog.controller.UserController.sendEmailToAuthor
2018-11-23 16:34:55.349 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 請求引數:[第二封郵件呢]
2018-11-23 16:34:55.350 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - ------------------------------------------------------
測試執行次數
方法之後執行...after.
方法執行完執行...afterRunning
2018-11-23 16:34:55.350 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 耗時(毫秒):0
2018-11-23 16:34:55.350 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - 返回資料:com.lmx.blog.common.Response@79f85428
2018-11-23 16:34:55.350 [http-nio-8888-exec-2] INFO c.l.blog.config.LogApsect - ==========================================>
顯而易見,該方法符合 @Around
環繞通知的匹配規則,所以進入了@Around
的邏輯,但是發現了問題,所有的方法都被執行了2次,不管是切面層還是方法層。(有人估計要問我不是用的自定義註解 @RedisCache(type = Response.class)
麼。為什麼會符合 @Around
的匹配規則呢,這個等會在下面說)
我們分析日誌的列印順序可以得出,在執行環繞方法時候,會優先進入 @Around
下的方法。@Around
的方法再貼一下程式碼。
// 定義需要匹配的切點表示式,同時需要匹配引數
@Around("pointCut() && args(arg)")
public Response around(ProceedingJoinPoint pjp,String arg) throws Throwable{
System.out.println("name:" + arg);
System.out.println("方法環繞start...around");
String result = null;
try{
result = pjp.proceed().toString() + "aop String";
System.out.println(result);
}catch (Throwable e){
e.printStackTrace();
}
System.out.println("方法環繞end...around");
return (Response) pjp.proceed();
}
列印了前兩行程式碼以後,轉而去執行了 @Before
方法,是因為中途觸發了 ProceedingJoinPoint.proceed()
方法。這個方法的作用是執行被代理的方法,也就是說執行了這個方法之後會執行我們controller的方法,而後執行 @before
,@after
,然後回到@Around執行未執行的方法,最後執行 @afterRunning
,如果有異常丟擲能執行 @AfterThrowing
也就是說環繞的執行順序是 @Around→@Before→@After→@Around
執行 ProceedingJoinPoint.proceed()
之後的操作→@AfterRunning
(如果有異常→@AfterThrowing
)
而我們上述的日誌相當於把上述結果執行了2遍,根本原因在於 ProceedingJoinPoint.proceed()
這個方法,可以發現在@Around 方法中我們使用了2次這個方法,然而每次呼叫這個方法時都會走一次@Before→@After→@Around
執行 ProceedingJoinPoint.proceed()
之後的操作→@AfterRunning
(如果有異常→@AfterThrowing
)。因此問題是出現在這裡。所以更改@Around
部分的程式碼即可解決該問題。更改之後的程式碼如下:
@Around("pointCut() && args(arg)")
public Response around(ProceedingJoinPoint pjp,String arg) throws Throwable{
System.out.println("name:" + arg);
System.out.println("方法環繞start...around");
String result = null;
Object object = pjp.proceed();
try{
result = object.toString() + "aop String";
System.out.println(result);
}catch (Throwable e){
e.printStackTrace();
}
System.out.println("方法環繞end...around");
return (Response) object;
}
更改程式碼之後的執行結果
name:第二封郵件呢
方法環繞start...around
方法執行前執行......before
2018-11-23 16:52:14.315 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - <=====================================================
2018-11-23 16:52:14.315 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 請求來源: =》0:0:0:0:0:0:0:1
2018-11-23 16:52:14.315 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 請求URL:http://localhost:8888/user/sendEmail
2018-11-23 16:52:14.315 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 請求方式:GET
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 響應方法:com.lmx.blog.controller.UserController.sendEmailToAuthor
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 請求引數:[第二封郵件呢]
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - ------------------------------------------------------
測試執行次數
com.lmx.blog.common.Response@1b1c76afaop String
方法環繞end...around
方法之後執行...after.
方法執行完執行...afterRunning
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 耗時(毫秒):0
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - 返回資料:com.lmx.blog.common.Response@1b1c76af
2018-11-23 16:52:14.316 [http-nio-8888-exec-4] INFO c.l.blog.config.LogApsect - ==========================================>
回到上述未解決的問題,為什麼我定義了切面的另一個註解還可以進入@Around方法呢?
因為我們的方法仍然在controller下,因此滿足該需求,如果我們定義了controller包下的某個controller才有用。例如:
@Pointcut("execution(public * com.lmx.blog.controller.UserController.*(..))")
而如果我們剛才定義的方法是寫在 TestController 之下的,那麼就不符合 @Around
方法的匹配規則了,也不符合@before
和@after
的註解規則,因此不會匹配任何一個規則,如果需要匹配特定的方法,可以用自定義的註解形式或者特性controller下的方法
①:特性的註解形式
@Pointcut("@annotation(com.lmx.blog.annotation.RedisCache)")
@Order(1) // Order 代表優先順序,數字越小優先順序越高
public void annoationPoint(){};
然後在所需要的方法上加入 @RedisCache
註解,在@Before
,@After
,@Around
等方法上新增該切點的方法名(“annoationPoint()
”),如果有多個註解需要匹配則用 ||
隔開
②:指定controller或者指定controller下的方法
@Pointcut("execution(public * com.lmx.blog.controller.UserController.*(..))")
@Order(2)
public void pointCut(){};
該部分程式碼是指定了 com.lmx.blog.controller
包下的UserController下的所有方法。
第一個*
代表的是返回型別不限
第二個*
代表的是該controller下的所有方法,(..)
代表的是引數不限
總結
當方法符合切點規則不符合環繞通知的規則時候,執行的順序如下
@Before→@After→@AfterRunning(如果有異常→@AfterThrowing)
當方法符合切點規則並且符合環繞通知的規則時候,執行的順序如下
@Around→@Before→@Around→@After執行 ProceedingJoinPoint.proceed() 之後的操作→@AfterRunning(如果有異常→@AfterThrowing)
原文連結:http://blog.csdn.net/lmx125254/article/details/84398412
版權宣告:本文為CSDN博主「Leonis丶L」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2021最新版)
2.別在再滿屏的 if/ else 了,試試策略模式,真香!!
3.臥槽!Java 中的 xx ≠ null 是什麼新語法?
4.Spring Boot 2.5 重磅釋出,黑暗模式太炸了!
覺得不錯,別忘了隨手點贊+轉發哦!
- 有了 for (;;) 為什麼還需要 while (true) ? 到底哪個更快?
- 再見,Spring Security OAuth!!
- Spring Boot Vue Shiro 實現前後端分離、許可權控制
- Java 技術棧中介軟體優雅停機方案設計與實現全景圖
- Java 技術棧中介軟體優雅停機方案設計與實現全景圖
- JHipster:Java和JavaScript的全棧框架
- 面試官:Spring 註解 @After,@Around,@Before 的執行順序是?
- C 與Java“相愛相殺”:一個步步緊逼,一個節節敗退
- C 即將超越Java、360企業安全雲或將上線“一鍵強制下班”功能、Glibc增加面向Arm SVE優化的記憶體拷貝 ...
- 面向開發人員的映象和容器實踐指南
- 面試官:生成訂單 30 分鐘未支付,則自動取消,該怎麼實現?
- 臥槽!!IntelliJ IDEA 居然偷偷改程式碼。。
- 鑑權 5 兄弟:cookie、session、token、jwt、單點登入,終於有人說清楚了!
- 高逼格的 SQL 寫法:行行比較,別問為什麼,問就是逼格高。。
- 你見過最垃圾的程式碼長什麼樣?(來長長見識)
- 不捲了!技術團隊成員集體辭職
- 引爆全球的 Log4j2 核彈級漏洞,JNDI 到底是個什麼鬼?
- TIOBE 1月程式語言排行榜出爐:Python蟬聯冠軍,C和JAVA分列二三
- 再見,CentOS!2021/12/31 宣佈正式停服。。
- 基於 ElasticSearch 實現站內全文搜尋,寫得太好了!