《Spring AOP》-----各种通知解析

前言

  • 上一篇文章中,小编简单介绍了SpringAop中的一些概念,意义、还有简单入门的小例子,那么现在小编带着读者解析一下SpringAop中的几种通知,所谓的通知,就是切面中的几种方法。

1、前置通知(切面类方法)

        /*
         * 在目标方法执行之前执行
         * 参数:连接点
         */
        public void beginTransaction(JoinPoint joinPoint){
            String methodName = joinPoint.getSignature().getName();
            System.out.println("连接点的名称:"+methodName);
            System.out.println("目标类:"+joinPoint.getTarget().getClass());
            System.out.println("begin transaction");
        }

配置文件

<aop:before method="beginTransaction" pointcut-ref="perform"/>

2、后置通知(切面类方法)

    /**
     *     在目标方法执行之后执行
     *     参数:连接点、目标方法返回值
     */
    public void commit(JoinPoint joinPoint,Object val){
        System.out.println("目标方法的返回值:"+val);
        System.out.println("commit");
    }

配置文件

      <!-- 
           1、后置通知可以获取到目标方法的返回值
           2、当目标方法抛出异常,后置通知将不再执行
     -->
    <aop:after-returning method="commit" pointcut-ref="perform" returning="val"/>

3、最终通知(切面类方法)

public void finallyMethod(){
        System.out.println("finally method");
    }

配置文件

     <!-- 
           无论目标方法是否抛出异常都将执行
     -->
     <aop:after method="finallyMethod" pointcut-ref="perform"/>

4、异常通知(切面类方法)

/**
 *    接受目标方法抛出的异常
 *    参数:连接点、异常
 */
    public void throwingMethod(JoinPoint joinPoint,Throwable ex){
        System.out.println(ex.getMessage());
    }

配置文件

    <!-- 
        异常通知
     -->
  <aop:after-throwing method="throwingMethod" throwing="ex" pointcut-ref="perform"/>

5、环绕通知(切面类方法)

/**
 *   joinPoint.proceed();这个代码如果在环绕通知中不写,则目标方法不再执行
 *  参数:ProceedingJoinPoint 
 */
    public void aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("aaaa");
        joinPoint.proceed();//调用目标方法
    }

配置文件

<!-- 
       能控制目标方法的执行  
-->
    <aop:around method="aroundMethod" pointcut-ref="perform"/>

小结:

  • 前置通知是在目标方法执行之前执行;后置通知是在目标方法执行之后执行,但是目标方法如果有异常,后置通知不在执行;而最终通知无论目标方法有没有异常都会执行;异常通知是捕获异常使用的;环绕通知能控制目标方法的执行。这就是以上的几种通知。小编将配置文件简单化,如果读者想拿代码测试一下的话,可以结合着Spring
    Aop入门将代码补全。
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 29
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值