Spring中方法拦截器

编程入门 行业动态 更新时间:2024-10-28 20:23:53

Spring中<a href=https://www.elefans.com/category/jswz/34/1771314.html style=方法拦截器"/>

Spring中方法拦截器

一、MethodInterceptor

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

这里的包一定要导正确

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;public class Around implements MethodInterceptor {// methodInvocation是目标对象中需要添加额外功能的方法@Overridepublic 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接口可以让我们的额外功能变得更加灵活,其实这里不只是能运行在目标方法之后,其实还可以前后都运行(我们常说的环绕通知)、也可以在抛出异常之后运行等,这里就不再演示了

更多推荐

Spring中方法拦截器

本文发布于:2023-12-04 11:15:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1660728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   拦截器   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!