文章目錄
- 一、Spring Boot AOP簡介
- 二、通知順序
- 1. 通知類型及其順序
- 示例代碼
- 2. 控制通知順序
- 示例代碼
一、Spring Boot AOP簡介
AOP(Aspect-Oriented Programming,面向切面編程)是對OOP(Object-Oriented Programming,面向對象編程)的補充。AOP通過預編譯方式和運行期動態代理實現在不修改源代碼的情況下給程序動態統一添加功能的一種技術。
在Spring Boot中,AOP主要通過注解和AspectJ來實現。主要的AOP注解有:
@Aspect
:定義切面類@Before
:前置通知@After
:后置通知@AfterReturning
:返回通知@AfterThrowing
:異常通知@Around
:環繞通知
二、通知順序
1. 通知類型及其順序
在Spring AOP中,通知按以下順序執行:
@Around
(環繞通知)前半部分@Before
(前置通知)- 被代理的方法執行
@AfterReturning
(返回通知)或@AfterThrowing
(異常通知)@After
(后置通知)@Around
(環繞通知)后半部分
示例代碼
@Aspect
@Component
public class LoggingAspect {@Before("execution(* com.example.service.*.*(..))")public void logBefore(JoinPoint joinPoint) {System.out.println("logBefore() is running!");}@After("execution(* com.example.service.*.*(..))")public void logAfter(JoinPoint joinPoint) {System.out.println("logAfter() is running!");}@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")public void logAfterReturning(JoinPoint joinPoint, Object result) {System.out.println("logAfterReturning() is running!");}@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "error")public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {System.out.println("logAfterThrowing() is running!");}@Around("execution(* com.example.service.*.*(..))")public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("logAround() before is running!");Object result = joinPoint.proceed();System.out.println("logAround() after is running!");return result;}
}
2. 控制通知順序
在不同的切面之間定義通知的執行順序。可以使用@Order
注解。
示例代碼
@Aspect
@Order(1)
@Component
public class FirstAspect {@Before("execution(* com.example.service.*.*(..))")public void beforeAdvice() {System.out.println("FirstAspect beforeAdvice()");}
}@Aspect
@Order(2)
@Component
public class SecondAspect {@Before("execution(* com.example.service.*.*(..))")public void beforeAdvice() {System.out.println("SecondAspect beforeAdvice()");}
}
FirstAspect
的beforeAdvice
會先于SecondAspect
的beforeAdvice
執行。