1. 程式人生 > >DispatcherServlet的初始化(二)

DispatcherServlet的初始化(二)

err root roo dha 其他 還需要 not led end

DispatcherServlet的初始化在springmvc的啟動中有講過,這一篇在上一篇的基礎上接著講。DispatcherServlet作為springmvc的前端控制器,還需要初始化其他的模塊。

回到initWebApplicationContext()函數,看到在wac = createWebApplicationContext(rootContext)後面,調用了onRefresh(was)函數,onRefresh函數在DispatcherServlet類中重寫,代碼如下:

/**
     * This implementation calls {@link #initStrategies}.
     
*/ @Override protected void onRefresh(ApplicationContext context) { initStrategies(context); }

可以看到MVC初始化是在DispatcherServlet的initStrategies()方法中完成,在該方法中初始化各種MVC框架實現元素,如至此request映射的HandlerMappings,以及handler適配處理器HandlerAdapters,以及視圖生成器ViewResolver等。

/**
     * Initialize the strategy objects that this servlet uses.
     * <p>May be overridden in subclasses in order to initialize further strategy objects.
     
*/ protected void initStrategies(ApplicationContext context) { initMultipartResolver(context); initLocaleResolver(context); initThemeResolver(context); initHandlerMappings(context); initHandlerAdapters(context); initHandlerExceptionResolvers(context); initRequestToViewNameTranslator(context); initViewResolvers(context); initFlashMapManager(context); }

比如初始化HandlerMappings,在SpringMVC中,HandlerMappings的作用是為Http請求找到對應的Controller控制器,來進一步處理請求。

    /**
     * Initialize the HandlerMappings used by this class.
     * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
     * we default to BeanNameUrlHandlerMapping.
     */
    private void initHandlerMappings(ApplicationContext context) {
        this.handlerMappings = null;

        if (this.detectAllHandlerMappings) {
            // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
            Map<String, HandlerMapping> matchingBeans =
                    BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
                // We keep HandlerMappings in sorted order.
                AnnotationAwareOrderComparator.sort(this.handlerMappings);
            }
        }
        else {
            try {
                HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
                this.handlerMappings = Collections.singletonList(hm);
            }
            catch (NoSuchBeanDefinitionException ex) {
                // Ignore, we‘ll add a default HandlerMapping later.
            }
        }

        // Ensure we have at least one HandlerMapping, by registering
        // a default HandlerMapping if no other mappings are found.
        if (this.handlerMappings == null) {
            this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
            if (logger.isDebugEnabled()) {
                logger.debug("No HandlerMappings found in servlet ‘" + getServletName() + "‘: using default");
            }
        }
    }
detectAllHandlerMappings變量默認為true,所以在初始化HandlerMapping接口默認實現類的時候,會把上下文中所有HandlerMapping類型的Bean都註冊在handlerMappings這個List變量中。如果你手工將其設置為false,那麽將嘗試獲取名為handlerMapping的Bean,新建一個只有一個元素的List,將其賦給handlerMappings。如果經過上面的過程,handlerMappings變量仍為空,那麽說明你沒有在上下文中提供自己HandlerMapping類型的Bean定義。此時,SpringMVC將采用默認初始化策略來初始化handlerMappings。
點進去getDefaultStrategies看一下。


/**
     * Create a List of default strategy objects for the given strategy interface.
     * <p>The default implementation uses the "DispatcherServlet.properties" file (in the same
     * package as the DispatcherServlet class) to determine the class names. It instantiates
     * the strategy objects through the context‘s BeanFactory.
     * @param context the current WebApplicationContext
     * @param strategyInterface the strategy interface
     * @return the List of corresponding strategy objects
     */
    @SuppressWarnings("unchecked")
    protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
        String key = strategyInterface.getName();
        String value = defaultStrategies.getProperty(key);
        if (value != null) {
            String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
            List<T> strategies = new ArrayList<T>(classNames.length);
            for (String className : classNames) {
                try {
                    Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
                    Object strategy = createDefaultStrategy(context, clazz);
                    strategies.add((T) strategy);
                }
                catch (ClassNotFoundException ex) {
                    throw new BeanInitializationException(
                            "Could not find DispatcherServlet‘s default strategy class [" + className +
                                    "] for interface [" + key + "]", ex);
                }
                catch (LinkageError err) {
                    throw new BeanInitializationException(
                            "Error loading DispatcherServlet‘s default strategy class [" + className +
                                    "] for interface [" + key + "]: problem with class file or dependent class", err);
                }
            }
            return strategies;
        }
        else {
            return new LinkedList<T>();
        }
    }

這個DispatcherServlet.properties裏面,以鍵值對的方式,記錄了SpringMVC默認實現類,它在spring-webmvc-4.2.5.RELEASE.jar這個jar包內,在org.springframework.web.servlet包裏面。

# Default implementation classes for DispatcherServlet‘s strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.

org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver

org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,    org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,    org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

至此,我們分析完了initHandlerMappings(context)方法的執行過程,其他的初始化過程與這個方法非常類似。所有初始化方法執行完後,SpringMVC正式完成初始化,靜靜等待Web請求的到來。

DispatcherServlet的初始化(二)