男男互做网站,我在学校志愿队做网站的经历,六安裕安区,市场营销策划案的范文文章目录 一、Spring Boot AOP简介二、通知顺序1. 通知类型及其顺序示例代码 2. 控制通知顺序示例代码 一、Spring Boot AOP简介
AOP#xff08;Aspect-Oriented Programming#xff0c;面向切面编程#xff09;是对OOP#xff08;Object-Oriented Programming#xff0c… 文章目录 一、Spring Boot AOP简介二、通知顺序1. 通知类型及其顺序示例代码 2. 控制通知顺序示例代码 一、Spring Boot AOP简介
AOPAspect-Oriented Programming面向切面编程是对OOPObject-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执行。