關(guān)于 Spring AOP 的 5 種通知類型,很少人知道它的優(yōu)先級!
點擊關(guān)注公眾號,Java干貨及時送達(dá)
真香!24W字的Java面試手冊(點擊查看)
作者:其樂m
來源:my.oschina.net/u/4115134/blog/3216359
前言
這篇比較簡單,但是群友反饋面試被問到了,關(guān)鍵還沒答出來,而且還是項目中用的比較多的技術(shù)點。還是要在平時開發(fā)中有一丟丟好奇心,多點進去看看代碼啊!
通知類型
在基于Spring AOP編程的過程中,基于AspectJ框架標(biāo)準(zhǔn),spring中定義了五種類型的通知,它們分別是:
前置通知 (@Before) 。 返回通知 (@AfterReturning) 。 異常通知 (@AfterThrowing) 。 后置通知 (@After)。 環(huán)繞通知 (@Around) :(優(yōu)先級最高)
通知執(zhí)行順序
將上面的所有通知類型寫入同一個切面中,它的執(zhí)行順序為:

代碼展示
package com.cy.pj.common.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SysTimeAspect {
/**
* 切入點
*/
@Pointcut("bean(sysMenuServiceImpl)")
public void doTime(){}
@Before("doTime()")
public void doBefore(JoinPoint jp){
System.out.println("time doBefore()");
}
@After("doTime()")
public void doAfter(){//類似于finally{}代碼塊
System.out.println("time doAfter()");
}
/**核心業(yè)務(wù)正常結(jié)束時執(zhí)行
* 說明:假如有after,先執(zhí)行after,再執(zhí)行returning*/
@AfterReturning("doTime()")
public void doAfterReturning(){
System.out.println("time doAfterReturning");
}
/**核心業(yè)務(wù)出現(xiàn)異常時執(zhí)行
* 說明:假如有after,先執(zhí)行after,再執(zhí)行Throwing*/
@AfterThrowing("doTime()")
public void doAfterThrowing(){
System.out.println("time doAfterThrowing");
}
@Around("doTime()")
public Object doAround(ProceedingJoinPoint jp)
throws Throwable{
System.out.println("doAround.before");
try {
Object obj=jp.proceed();
return obj;
}catch(Throwable e) {
System.out.println("doAround.error-->"+e.getMessage());
throw e;
}finally {
System.out.println("doAround.after");
}
}
}
代碼正常結(jié)束

代碼出現(xiàn)異常

如有文章對你有幫助,
歡迎關(guān)注??、點贊??、轉(zhuǎn)發(fā)??!
推薦, Java面試手冊 內(nèi)容包括網(wǎng)絡(luò)協(xié)議、Java基礎(chǔ)、進階、字符串、集合、并發(fā)、JVM、數(shù)據(jù)結(jié)構(gòu)、算法、MySQL、Redis、Mongo、Spring、SpringBoot、MyBatis、SpringCloud、Linux以及各種中間件(Dubbo、Nginx、Zookeeper、MQ、Kafka、ElasticSearch)等等... 點擊文末“閱讀原文”可直達(dá)
評論
圖片
表情

