AbstractHandlerMapping 的三个interceptor集合

AbstractHandlerMapping 主要干什么

AbstractHandlerMapping 主要定义写好了创建 HandlerExecutionChain 的需要必要参数,和流程,主要就是怎么找到,整理Interceptors和getHandler()方法,这个文章说的很简单,就是说一说这里有三个interceptor,源码如下

private final List<Object> interceptors = new ArrayList<Object>();

private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>();

private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>();

List< Object > interceptors

大家注意这逼是object 的类型的,不是interceptor,他是在创建AbstractHandlerMapping零时存一下东西,后面会在 initInterceptors()方法中,遍历它,把他分类到其他两个集合中。源码如下

protected void initInterceptors() {
		if (!this.interceptors.isEmpty()) {
			for (int i = 0; i < this.interceptors.size(); i++) {
				Object interceptor = this.interceptors.get(i);
				if (interceptor == null) {
					throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");
				}
				if (interceptor instanceof MappedInterceptor) {
					this.mappedInterceptors.add((MappedInterceptor) interceptor);
				}
				else {
					this.adaptedInterceptors.add(adaptInterceptor(interceptor));
				}
			}
		}
	}

注意!我一开始以为是,我们配置的interceptor全部都放到interceptors中,后面发现和interceptors和我们日常使用关系不大,他只有两种方式可以配置

  1. 我们继承重写 extendInterceptors(),源码如下
@Override
	protected void initApplicationContext() throws BeansException {
		extendInterceptors(this.interceptors);
		detectMappedInterceptors(this.mappedInterceptors);
		initInterceptors();
	}

protected void extendInterceptors(List<Object> interceptors) {
	}

这里提供了一个钩子,会把interceptors传给我们,我们这里有一个机会来在interceptors中间加东西,这样后面就可以通过上面说的分类操作,来分到其他两个集合

  1. 配置的方式,在注册这个handlerMapping,同时配置interceptor,这个方法
public void setInterceptors(Object... interceptors) {
		this.interceptors.addAll(Arrays.asList(interceptors));
	}

List

这个现在是直接在每一个handlerMapping中都有一份,会直接被放到HandlerExecutionChain中等待被执行,因为他根本没有判断拦截的条件,都运行

List mappedInterceptors

这个是我们频繁使用的,我们在xml中配置的就是这个东西,这个只要被加载到spingappliactionContext中就会被加载发现到 handlermapping中,原理在上两篇文章中有。

ps; 我发现在spring-webmvc 4.3.5 之后,第3个没有了,直接让 MappedInterceptor继承MappedInterceptor,也就是不存在不带拦截url条件的interceptor了,所有的interceptor都是MappedInterceptor了,哎发展的很快!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章