【Spring Boot AOP通知顺序】


一、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中,通知按以下顺序执行:

  1. @Around(环绕通知)前半部分
  2. @Before(前置通知)
  3. 被代理的方法执行
  4. @AfterReturning(返回通知)或@AfterThrowing(异常通知)
  5. @After(后置通知)
  6. @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()");
    }
}

FirstAspectbeforeAdvice会先于SecondAspectbeforeAdvice执行。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值