首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

spring 拦截器施用的例子

2012-11-04 
spring 拦截器使用的例子转自:http://blog.csdn.net/lemonfamily/article/details/1498246spring 拦截器是

spring 拦截器使用的例子
转自:http://blog.csdn.net/lemonfamily/article/details/1498246

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[i].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"  >    <value>userDAO</value><!-- 在这里可以声明多个需要拦截的bean --></property><property name= "interceptorNames" >  <list>  <value>logger</value><!-- 同样,在这里可以声明多个拦截器,注意次序前后 --> </list></property></bean>

拦截器在spring中一般都是用来类似过滤器的功能,如日志处理、编码转换、权限检查等。以后仍会对spring的拦截器进行更加深入的研究。

热点排行