Interceptor有三個類型的List:算法
AbstractHandlerMapping的建立其實就是初始化這三個interceptorapp
private final List<Object> interceptors = new ArrayList<Object>(); private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>(); private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>();
AbstractHandlerMapping初始化會自動調用initApplicationContext。ide
@Override protected void initApplicationContext() throws BeansException { //模板方法,用於給子類提供一個添加Interceptors的入口。 extendInterceptors(this.interceptors); //將SpringMvc容器和父容器中全部的MappedInterceptor類型的Bean添加到mappedInterceptors的屬性 detectMappedInterceptors(this.mappedInterceptors); //用於初始化Interceptor,將Interceptors屬性裏所包含的對象按類型添加到mappedInterceptors和adaptedInterceptors. initInterceptors(); }
HandlerMapping是經過getHandler方法來獲取處理器Handler和攔截器Interceptors的。下面看下AbstractHandlerMapping的實現。學習
@Override public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { //一、經過getHandlerInternal方法獲取,這是個模板方法。 Object handler = getHandlerInternal(request); if (handler == null) { //二、若是沒有獲取到則使用默認的Handler handler = getDefaultHandler(); } if (handler == null) { return null; } //三、若是是String類型,則以它爲名到SpringMvc的容器裏查找相應的Bean。 if (handler instanceof String) { String handlerName = (String) handler; handler = getApplicationContext().getBean(handlerName); } return getHandlerExecutionChain(handler, request); }
getHandlerExecutionChain以前用於找Handler,以後用於添加攔截器。getHandlerExecutionChain的實現使用handler建立出HandlerExecutionChain類型的變量,而後將adaptedInterceptors和符合要求的mappedInterceptors添加進去,最後將其返回。this
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { //建立HandlerExecutionChain HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ? (HandlerExecutionChain) handler : new HandlerExecutionChain(handler)); //添加全部AdaptedInterceptor的攔截器 chain.addInterceptors(getAdaptedInterceptors()); String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); //與請求url進行匹配,知足的才加入 for (MappedInterceptor mappedInterceptor : this.mappedInterceptors) { if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) { chain.addInterceptor(mappedInterceptor.getInterceptor()); } } return chain; }
總結:url
AbstractHandlerMapping已經實現了攔截器的初始化,因此子類的主要任務是實現模板方法getHandlerInternal來查找對應的Handler。spa
歡迎加入Java學習交流羣點擊:484757838
設計