Spring AOP多个切面执行顺序

整体顺序图

网图:
image

实验

controller

@Slf4j
@RequestMapping("/demo")
@RestController
public class DemoController {

    @GetMapping("/doAopTest")
    public String doAopTest() {
        log.info("==============> doAopTest");
        return "doAopTest";
    }
}

切面1

@Slf4j
@Order(1)
@Component
@Aspect
public class OneAspect {

    @Pointcut("execution(* cn.sunpy.demo.controller.DemoController.doAopTest())")
    public void cut() {

    }

    @Before("cut()")
    public void beforeExe() {
        log.info("==============> OneAspect.beforeExe");
    }

    @After("cut()")
    public void afterExe() {
        log.info("==============> OneAspect.afterExe");
    }

    @Around("cut()")
    public Object aroundExe(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("==============> OneAspect.aroundExe first");
        Object result = joinPoint.proceed();
        log.info("==============> OneAspect.aroundExe final");
        return result;
    }

    @AfterReturning("cut()")
    public void afterReturnExe() {
        log.info("==============> OneAspect.afterReturnExe first");
    }

    @AfterThrowing("cut()")
    public void afterThrowing() {
        log.info("==============> OneAspect.afterThrowing first");
    }

}

切面2

@Slf4j
@Order(2)
@Component
@Aspect
public class TwoAspect {

    @Pointcut("execution(* cn.sunpy.demo.controller.DemoController.doAopTest())")
    public void cut() {

    }

    @Before("cut()")
    public void beforeExe() {
        log.info("==============> TwoAspect.beforeExe");
    }

    @After("cut()")
    public void afterExe() {
        log.info("==============> TwoAspect.afterExe");
    }

    @Around("cut()")
    public Object aroundExe(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("==============> TwoAspect.aroundExe first");
        Object result = joinPoint.proceed();
        log.info("==============> TwoAspect.aroundExe final");
        return result;
    }

    @AfterReturning("cut()")
    public void afterReturnExe() {
        log.info("==============> TwoAspect.afterReturnExe first");
    }

    @AfterThrowing("cut()")
    public void afterThrowing() {
        log.info("==============> TwoAspect.afterThrowing first");
    }
}

结果:
image

总结

  1. 切面1-Around start
  2. 切面1-Before
  3. 切面2-Around start
  4. 切面2-Before
  5. 业务方法
  6. 切面2-AfterReturning
  7. 切面2-After
  8. 切面2-Around end
  9. 切面1-AfterReturning
  10. 切面1-After
  11. 切面1-Around end
posted @ 2023-09-19 17:11  sunpeiyu  阅读(479)  评论(0编辑  收藏  举报