spring 拦截器的实现

    技术2022-05-11  11

     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"  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的拦截器进行更加深入的研究。


    最新回复(0)