spring之aop整理

好久不怎么用,今天整理一下

前置通知 @Before 目标方法执行之前

后置通知 @After  目标方法执行后,不管目标方法执行是否异常,该方法都会执行

返回通知 @AfterReturning 返回通知是可以访问到方法的返回值的 result

异常通知 @AfterThrowing 在目标方法出现异常时会执行

环绕通知 环绕通知类似于动态代理的全过程 必须有返回值, 返回值即为目标方法的返回值

执行顺序:

   正常:

       

 

   异常:

       

 

@Aspect  

public class TestAnnotationAspect {  

  

    @Pointcut("execution(* com.spring.service.*.*(..))")  

    private void pointCutMethod() {  

    }  

  

    //声明前置通知  目标方法执行之前

    @Before("pointCutMethod()")  

    public void doBefore(JoinPoint joinPoint) {  

        String methodName = joinPoint.getSignature().getName();

        System.out.println("前置通知");  

    }

    //声明后置通知  目标方法执行后,不管目标方法执行是否异常,该方法都会执行

    @After("pointCutMethod()")  

    public void doAfter(JoinPoint joinPoint) {  

        System.out.println("后置通知");  

    }  

  

    //声明返回通知  返回通知是可以访问到方法的返回值的 result

    @AfterReturning(value = "pointCutMethod()", returning = "result")  

    public void doAfterReturning(JoinPoint joinPoint,Object result) {  

        System.out.println("返回通知");  

        System.out.println("---" + result + "---");  

    }  

  

    //声明异常通知  在目标方法出现异常时会执行

    @AfterThrowing(value = "pointCutMethod()", throwing = "e")  

    public void doAfterThrowing(JoinPoint joinPoint,Exception e) {  

        System.out.println("异常通知");  

        System.out.println(e.getMessage());  

    }  

  

   

  

    /**

     * 环绕通知需要携带 ProceedingJoinPoint 类型的参数. 

     * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.

      * 且环绕通知必须有返回值, 返回值即为目标方法的返回值

      */

/*

@Around("pointCutMethod()")

public Object aroundMethod(ProceedingJoinPoint pjd){

   Object result = null;

   String methodName = pjd.getSignature().getName();

   try {

       //前置通知

      System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));

      //执行目标方法

      result = pjd.proceed();

      //返回通知

      System.out.println("The method " + methodName + " ends with " + result);

   } catch (Throwable e) {

       //异常通知

       System.out.println("The method " + methodName + " occurs exception:" + e);

       throw new RuntimeException(e);

    }

   //后置通知

   System.out.println("The method " + methodName + " ends");

   return result;

}

*/ 

}  

/**

 *这个注解可以指定切面的优先级  越小优先级越高

 *

 */

@Order(1)

   

猜你喜欢

转载自zzgo20141028.iteye.com/blog/2370754