通知類型
在基於Spring AOP編程的過程中,基於AspectJ框架標準,spring中定義了五種類型的通知,它們分別是:
- 前置通知 (@Before) 。
- 返回通知 (@AfterReturning) 。
- 異常通知 (@AfterThrowing) 。
- 後置通知 (@After)。
- 環繞通知 (@Around) :(優先級最高)
通知執行順序
將上面的所有通知類型寫入同一個切面中,它的執行順序爲:
代碼展示
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()");
}
/**核心業務正常結束時執行
* 說明:假如有after,先執行after,再執行returning*/
@AfterReturning("doTime()")
public void doAfterReturning(){
System.out.println("time doAfterReturning");
}
/**核心業務出現異常時執行
* 說明:假如有after,先執行after,再執行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");
}
}
}