通知类型

在基于Spring AOP编程的过程中,基于AspectJ框架标准,spring中定义了五种类型的通知,它们分别是:

  • 前置通知 (@Before)
  • 返回通知 (@AfterReturning)
  • 异常通知 (@AfterThrowing)
  • 后置通知 (@After)
  • 环绕通知 (@Around) :(优先级最高)

    通知执行顺序

    将上面的所有通知类型写入同一个切面中,它的执行顺序为:
    image.png

    测试代码

    ```java 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 {

  1. @Pointcut("bean(sysMenuServiceImpl)")
  2. public void doTime(){}
  3. @Before("doTime()")
  4. public void doBefore(JoinPoint jp){
  5. System.out.println("time doBefore()");
  6. }
  7. @After("doTime()")
  8. public void doAfter(){//类似于finally{}代码块
  9. System.out.println("time doAfter()");
  10. }
  11. @AfterReturning("doTime()")
  12. public void doAfterReturning(){
  13. System.out.println("time doAfterReturning");
  14. }
  15. @AfterThrowing("doTime()")
  16. public void doAfterThrowing(){
  17. System.out.println("time doAfterThrowing");
  18. }
  19. @Around("doTime()")
  20. public Object doAround(ProceedingJoinPoint jp)
  21. throws Throwable{
  22. System.out.println("doAround.before");
  23. try {
  24. Object obj=jp.proceed();
  25. return obj;
  26. }catch(Throwable e) {
  27. System.out.println("doAround.error-->"+e.getMessage());
  28. throw e;
  29. }finally {
  30. System.out.println("doAround.after");
  31. }
  32. }

} ```

代码正常结束

image.png

代码出现异常

image.png

来源:https://my.oschina.net/u/4115134/blog/3216359