Spring AOP有哪些通知類型,它們的執(zhí)行順序是怎樣的?
點(diǎn)擊上方 好好學(xué)java ,選擇 星標(biāo) 公眾號(hào)
重磅資訊,干貨,第一時(shí)間送達(dá) 今日推薦:14 個(gè) github 項(xiàng)目!
個(gè)人原創(chuàng)100W +訪問(wèn)量博客:點(diǎn)擊前往,查看更多
前言
這篇比較簡(jiǎn)單,但是群友反饋面試被問(wèn)到了,關(guān)鍵還沒(méi)答出來(lái),而且還是項(xiàng)目中用的比較多的技術(shù)點(diǎn)。還是要在平時(shí)開發(fā)中有一丟丟好奇心,多點(diǎn)進(jìn)去看看代碼?。?/p>
通知類型
在基于Spring AOP編程的過(guò)程中,基于AspectJ框架標(biāo)準(zhǔn),spring中定義了五種類型的通知,它們分別是:
前置通知 (@Before) 。 返回通知 (@AfterReturning) 。 異常通知 (@AfterThrowing) 。 后置通知 (@After)。 環(huán)繞通知 (@Around) :(優(yōu)先級(jí)最高)
通知執(zhí)行順序
將上面的所有通知類型寫入同一個(gè)切面中,它的執(zhí)行順序?yàn)椋?/p>
代碼展示
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 {
/**
* 切入點(diǎn)
*/
@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é)束時(shí)執(zhí)行
* 說(shuō)明:假如有after,先執(zhí)行after,再執(zhí)行returning*/
@AfterReturning("doTime()")
public void doAfterReturning(){
System.out.println("time doAfterReturning");
}
/**核心業(yè)務(wù)出現(xiàn)異常時(shí)執(zhí)行
* 說(shuō)明:假如有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)異常

作者:其樂(lè)m
來(lái)源:my.oschina.net/u/4115134/blog/3216359
推薦文章
更多項(xiàng)目源碼
評(píng)論
圖片
表情
