Spring应用手册-AOP(XML)-(9)-AOP-XML-环绕通知发布

戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注

AOP-XML-环绕通知发布

spring应用手册(第四部分)


所谓环绕通知就是在目标方法的前后可以通知增强,正因为这样的情况,所以环绕通知可以阻止方法的执行,或者修改方法的返回值。

环绕通知也可以传入一个参数ProceedingJoinPoint,ProceedingJoinPoint 是Joinpoint的一个子类,增强了一些方法,我们可以通过ProceedingJoinPoint 的proceed()调用被增强方法。

看案例:

业务方法:

/**
 * @author 戴着假发的程序员
 * @company http://www.boxuewa.com
 * @description
 */
public class MessageBean {
    //输出信息的业务方法
    public String printMessage(String msg){
        System.out.println("MessageBean-printMessage:"+msg);
        return msg;
    }
}

在Aspect类中添加环绕通知的处理业务方法:

/**
 * @author 戴着假发的程序员
 * @company http://www.boxuewa.com
 * @description
 */
public class DkAspect {
    /**
     * 环绕通知
     */
    public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
        Object retVal = null;
        System.out.println("--环绕通知开始--");
        //执行目标方法
        try {
            //这里可以根据条件判断是否要执行目标方法
            retVal = joinPoint.proceed();
            //可以修改目标方法返回值
            retVal = "环绕通知修改后的返回值";
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("--环绕通知结束--");
        return retVal;
    }

在aop:config中添加环绕通知的配置:

 <!-- AOP配置 -->
    <aop:config>
        <!-- 申明AspectBean,引用我们注册的dkAspect -->
        <aop:aspect id="aspect" ref="dkAspcet">
            <!-- 声明一个切入点,命名为pointcut1 -->
            <!-- xml中不能使用 && ,逻辑与要使用and,-->
            <!-- 如果我们的before增强方法中传入了参数msg,我就要使用args(msg)限定切入点 -->
            <aop:pointcut id="pointcut1"
                          expression="execution(* com.st.beans..*.*(..))"/>
            <!-- 配置环绕通知 -->
            <aop:around method="round" pointcut-ref="pointcut1"/>
        </aop:aspect>
    </aop:config>

执行业务方法测试:

ApplicationContext ac =
        new ClassPathXmlApplicationContext("applicationContext.xml");
MessageBean bean = ac.getBean(MessageBean.class);
String retVal = bean.printMessage("假发的穿戴技巧");
System.out.println("业务方法的返回值:"+retVal);

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴着假发的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值