Spring中方法拦截器

一、MethodInterceptor

在动态代理中要想添加一个额外功能,只要去实现MethodBeforeAdvice这个接口就行了,但是实现了这个接口的额外功能只能运行在目标类执行之前,如果是想在目标类执行之后呢?那这个需求就完成不了,所以我们这里引入一个新的接口MethodInterceptor(方法拦截器)使用这个接口可能完成在目标类执行的各个时间段都能成功执行。

这里的包一定要导正确

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class Around implements MethodInterceptor {
    // methodInvocation是目标对象中需要添加额外功能的方法
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        // 这里的proceed方法代表的就是目标方法运行
        Object ret = methodInvocation.proceed();
        //如果想要额外功能运行在目标方法之后,就在proceed方法后加上额外功能就行了
        System.out.println("-------额外功能运行在目标方法后-------log");

        // 这里的返回值其实就是目标方法的返回值
        return ret;
    }
}

将这个拦截器完成了之后,也是需要在配置文件中创建对象的

<bean id="around" class="com.gl.demo.proxy.Around"/>

创建了这个对象,之后引入额外功能的配置文件就不再是Before类了,而是这个Around类,切入点还是所有的方法

<bean id="userService" class="com.gl.demo.proxy.UserServiceImpl"/>

<bean id="around" class="com.gl.demo.proxy.Around"/>

<aop:config>
    <aop:pointcut id="pc" expression="execution(* *(..))"/>
    <aop:advisor advice-ref="around" pointcut-ref="pc"/>
</aop:config>

利用之前的测试代码,这里发现额外功能已经添加完成了,并且是在目标方法运行之后

public void test2() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config2.xml");
    UserService userService = (UserService) ctx.getBean("userService");
    userService.register();
    userService.login();
}

实现MethodInterceptor接口可以让我们的额外功能变得更加灵活,其实这里不只是能运行在目标方法之后,其实还可以前后都运行(我们常说的环绕通知)、也可以在抛出异常之后运行等,这里就不再演示了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值