Spring应用手册-AOP(XML)-(14)-AOP-XML-advisor-方式环绕通知

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

AOP-XML-advisor-方式环绕通知

spring应用手册(第四部分)


advisor的环绕通知,我们的通知类需要实现接口:MethodInterceptor,源码如下:

package org.aopalliance.intercept;

@java.lang.FunctionalInterface
public interface MethodInterceptor extends org.aopalliance.intercept.Interceptor {
    /**
     * 这里的参数methodInvocation扩展自Joinpoint,
     * 提供了获取目标对象,获取目标方法,获取目标方法参数列表的API。
     * 最终要的是提供了一个proceed方法,这个方法就是用来执行目标方法的。
     * @param methodInvocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable ;
}

我们自己定义一个环绕通知:

/**
 * @author 戴着假发的程序员
 * @company http://www.boxuewa.com
 * @description
 */
public class DkAroundAdvice implements MethodInterceptor {
    /**
     * 这里的参数methodInvocation扩展自Joinpoint,
     * 提供了获取目标对象,获取目标方法,获取目标方法参数列表的API。
     * 最终要的是提供了一个proceed方法,这个方法就是用来执行目标方法的。
     * @param methodInvocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("环绕通知开始--");
        System.out.println("目标对象:"+methodInvocation.getThis());
        System.out.println("被增加方法:"+methodInvocation.getMethod().getName());
        System.out.println("方法参数列表:"+ Arrays.toString(methodInvocation.getArguments()));
        //定义返回值
        Object retVal = null;
        //执行业务方法
        retVal = methodInvocation.proceed();
        System.out.println("环绕通知结束--");
        return retVal;
    }
}

注意这里的环绕通知和注解的环绕通知一样,都是在我们的拦截方法中执行业务方法,所以我们可以这我们的增强业务中根据条件选择执行业务方法或者不执行业务方法,可以调整业务方法的返回值。

配置环绕通知:

<!-- 环绕通知类注册 -->
    <bean id="aroundAdvice" class="com.st.advices.DkAroundAdvice"/>
<!-- AOP配置 -->
    <aop:config>
            <!-- 声明一个切入点,命名为pointcut1 -->
        <aop:pointcut id="pointcut1"
                          expression="execution(* com.st.beans..*.*(..))"/>
        <!-- 异常通知配置-->
        <aop:advisor advice-ref="aroundAdvice" pointcut-ref="pointcut1"/>
    </aop:config>

执行业务方法测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

戴着假发的程序员

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

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

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

打赏作者

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

抵扣说明:

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

余额充值