SpringAOP环绕通知的使用

上一篇文章介绍了SpringAOP的概念以及简单使用:SpringAOP概念及其使用

在springAOP中有五种通知,环绕通知是最为强大的通知。它能够让你编写的逻辑将被通知的目标方法完全包装起来。实际上就像在一个通知方法中同时编写前置通知和后置通知。
本片文章具体讲解环绕通知的使用。

使用注解

使用环绕通知定义切面:

@Aspect
    public class AudienceAround {
        //使用@Pointcut注解声明频繁使用的切入点表达式
        @Pointcut("execution(* com.wqh.concert.Performance.perform(..))")
        public void performance(){}

        @Around("performance()")
        public void watchPerformance(ProceedingJoinPoint joinPoint){

            try {
                System.out.println("Silencing cell phones");
                System.out.println("Taking seats");
                joinPoint.proceed();
                System.out.println("Demanding a refund");

            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

        }
    }

可以看到在上面的代码中,定义通知的时候在通知方法中添加了入参:ProceedingJoinPoint。在创建环绕通知的时候,这个参数是必须写的。因为在需要在通知中使用ProceedingJoinPoint.proceed()方法调用被通知的方法。

另外,如果忘记调用proceed()方法,那么通知实际上会阻塞对被通知方法的调用。

在XML中定义

首先去掉上面类的所有注解:这里为了区别就重新创建一个类

    public class AudienceAroundXML {
        public void watchPerformance(ProceedingJoinPoint joinPoint){
            try {
                System.out.println("Silencing cell phones");
                System.out.println("Taking seats");
                joinPoint.proceed();
                System.out.println("Demanding a refund");

            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

        }
    }

配置:

    <!--声明bean-->
    <bean name="audienceAroundXML" class="com.wqh.concert.AudienceAroundXML"/>
    <!--配置切面及通知-->
    <aop:config>
        <aop:aspect ref="audienceAroundXML">
            <aop:pointcut id="performance"
                          expression="execution(* com.wqh.concert.Performance.perform(..))"/>
            <aop:around method="watchPerformance" pointcut-ref="performance"/>
        </aop:aspect>
    </aop:config>
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值