欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何获取spring mvc中的拦截器的bean

程序员文章站 2022-07-13 14:54:45
...
举个例子Test2Interceptor要获取TestInterceptor来操作
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="com.xxx.TestInterceptor">	
		</bean>
	</mvc:interceptor>
        <mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="com.xxx.Test2Interceptor">		
		</bean>
	</mvc:interceptor>
</mvc:interceptors>

public class TestInterceptor implements HandlerInterceptor {

}

public class Test2Interceptor implements HandlerInterceptor,ApplicationContextAware {
        private ApplicationContext applicationContext;
        public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object object) throws Exception {
Map<String,MappedInterceptor> map = applicationContext.getBeansOfType(MappedInterceptor.class);
		for(MappedInterceptor m : map.values()) {
			if(m.getInterceptor() instanceof TestInterceptor) {
				System.out.println(m.getInterceptor());
			}
		}
        }
       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		
	}
}

得出原来spring mvc把<mvc:interceptors>配置的bean放到MappedInterceptor实例中
咱们看下MappedInterceptor源码
public final class MappedInterceptor {

	private final String[] includePatterns;

	private final String[] excludePatterns;

	private final HandlerInterceptor interceptor;
//省略
}

这里得出MappedInterceptor 持有HandlerInterceptor实例对象,HandlerInterceptor也就是我们刚刚写的拦截器的要实践的接口。
这样我们就明白了,大功告成。
相关标签: mvc spring