spring 拦截器的实现
spring 2009-09-14 11:00:02 阅读1065 评论0 字号:大中小 订阅
spring 拦截器是spring AOP体系下的一个重要的子功能。它类似于web中的filter,但又比filter灵活,强大得多。许多AOP框架,包括Spring,都是以拦截器做通知模型, 并维护一个以连接点为中心的拦截器链。(见Spring Framework 开发参考手册第6章),拦截功能是spring AOP实现面向切面编程的一个亮点,我们这里通过一个示例来看看如何使用拦截功能的:
这个例子是通过拦截指定的bean,在外部调用他们其中的方法被之前将触发拦截器。
首先,编写一个个拦截器:SpringAOPInterceptor.java
public class SpringAOPInterceptor implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("The Interceptor method name is: "
+ method.getDeclaringClass().getName() + "."
+ method.getName());
String value = "";
for(int i=0;ilength;i++){
value += args.toString()+"&";
}
System.out.println( "The method parames is:" +value);
System.out.println( "The target class is:" + target.getClass().getName());
}
该拦截器使用的是前置通知(before advice),它可以在该切入点也就是调用该方法前执行自定义的行为,但不能在切入点处理完返回过程中执行拦截,也就没办法改变切入点的返回值.如果想使用其他切入点进行拦截,可以查看org.springframework.aop包(Spring的通知API)下的其他类.
随后,我们可以编写几个需要被拦截的类,这里,我不再提供了,大家随便写个test类吧^_^.
最后,需要把拦截器注册到bean容器(applicationcontext.xml)内.并把要拦截的bean一起注入到自动代理bean定义类org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator中.
例子如下:
<bean name="logger" class="com.comwave.sc.form.ao010.test.SpringAOPInterceptor"method="dispose">
<bean name= "loggingAutoProxy"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name= "beanNames" >
<value>userDAO</value><!-- 在这里可以声明多个需要拦截的bean -->
</property>
<property name= "interceptorNames" >
<list>
<value>logger</value><!-- 同样,在这里可以声明多个拦截器,注意次序前后 -->
</list>
</property>
</bean>
拦截器在spring中一般都是用来类似过滤器的功能,如日志处理、编码转换、权限检查等。以后仍会对spring的拦截器进行更加深入的研究。
分享到:
相关推荐
spring拦截器,高级参数绑定,controller返回值
AOP拦截器示例,告诉我们初学者理解aop,通过一个银行转帐说明问题。
Spring AOP 拦截器 Advisor Spring AOP 拦截器 Advisor
NULL 博文链接:https://lpm528.iteye.com/blog/1259187
NULL 博文链接:https://rogerhunt.iteye.com/blog/608778
Spring MVC 拦截器Spring MVC 拦截器
spring-boot 拦截器 登录拦截spring-boot 拦截器 登录拦截spring-boot 拦截器 登录拦截spring-boot 拦截器 登录拦截
spring mvc 拦截器获取请求数据信息 解压之后放到项目中 直接运行就可以了 (将流多次运用)
使用CGLIB编写的Spring的拦截器 非常使用的哦
初学者很容易将 Spring MVC 拦截器 和 Spring Cloud OpenFeign 拦截器搞混,误以为OpenFeign拦截器就是SpringMVC拦截器:Spring MVC拦截器发生在客户端 和 服务端之间,在客户端向服务端发送请求时进行拦截处理。...
这一版本的项目中新增了拦截器的一个demo
自己spring boot 拦截器,可以自定义限制跳转路径及自定义不拦截哪些具体路径,具体设置可以看注释,一看就懂,引用哪些包已经包含了,不明白的请浏览,看到后第一时间给您回复
spring boot jpa连接数据库,设置拦截器拦截指定路径下的文件。
idea软件。SpringBoot的拦截器的博客所写的例子。preHandle()方法的返回值true和false的详细区别还未描述
springboot spring aop 拦截器 注解方式实现脱敏(涉及到:pom.xml -->application.properties --->启动类-->拦截器)
spring拦截器的简单例子.docx
Spring AOP四种创建通知(拦截器)类型
54-Spring设计模式之装饰器模式1
常用拦截 拦截器HandlerInterceptor 拦截器MethodInterceptor 添加依赖 创建启动类 创建拦截器类 创建控制器 监控control请求耗时,提高性能
针对spring boot 集成jpa sql操作进行自定义分库分表逻辑