当一个Web应用部署到容器内时(eg.tomcat),在Web应用开始响应执行用户请求前,如下步骤会被依次执行:css
web初始化流程图以下:前端
接下来以一个常见的简单web.xml配置进行Spring MVC启动过程的分析,web.xml配置内容以下:web
<web-app> <display-name>Web Application</display-name> <!--全局变量配置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-*.xml</param-value> </context-param> <!--监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--解决乱码问题的filter--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Restful前端控制器--> <servlet> <servlet-name>springMVC_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置servlet初始化优先级,本质是调用init()--> <load-on-startup>1<load-on-startup/> </servlet> <!--静态资源使用DefaultServletHttpRequestHandler处理器处理--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> </web-app>
在web初始化的时候会去加载web.xml文件,会按照配置的内容进行初始化spring
首先定义了<context-param>标签,用于配置一个全局变量,<context-param>标签的内容读取后会被放进application中,作为Web应用的全局变量使用,加载bean的时候做为application的configLocation参数,所以,Web应用在容器中部署后,进行初始化时会先读取这个全局变量,以后再进行上述讲解的初始化启动过程。
接着定义了一个ContextLoaderListener类的listener。查看ContextLoaderListener的类声明源码以下图:数据库
ContextLoaderListener类继承了ContextLoader类并实现了ServletContextListener接口,首先看一下前面讲述的ServletContextListener接口源码:tomcat
该接口只有两个方法contextInitialized和contextDestroyed,这里采用的是观察者模式,也称为为订阅-发布模式,实现了该接口的listener会向发布者进行订阅,当Web应用初始化或销毁时会分别调用上述两个方法。
继续看ContextLoaderListener,该listener实现了ServletContextListener接口,所以在Web应用初始化时会调用该方法,该方法的具体实现以下:安全
* Initialize the root web application context.*/ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
ContextLoaderListener的contextInitialized()方法直接调用了initWebApplicationContext()方法,这个方法是继承自ContextLoader类,经过函数名能够知道,该方法是用于初始化Web应用上下文,即IoC容器,这里使用的是代理模式,继续查看ContextLoader类的initWebApplicationContext()方法的源码以下:app
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { /* 首先经过WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 这个String类型的静态变量获取一个根IoC容器,根IoC容器做为全局变量 存储在application对象中,若是存在则有且只能有一个 若是在初始化根WebApplicationContext即根IoC容器时发现已经存在 则直接抛出异常,所以web.xml中只容许存在一个ContextLoader类或其子类的对象 */ if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. // 若是当前成员变量中不存在WebApplicationContext则建立一个根WebApplicationContext if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. //为根WebApplicationContext设置一个父容器 ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } //配置并刷新整个根IoC容器,在这里会进行Bean的建立和初始化 configureAndRefreshWebApplicationContext(cwac, servletContext); } } /* 将建立好的IoC容器放入到application对象中,并设置key为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 所以,在SpringMVC开发中能够在jsp中经过该key在application对象中获取到根IoC容器,进而获取到相应的Ben */ servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
initWebApplicationContext()方法如上注解讲述,主要目的就是建立root WebApplicationContext对象即根IoC容器,其中比较重要的就是,整个Web应用若是存在根IoC容器则有且只能有一个,根IoC容器做为全局变量存储在ServletContext即application对象中。将根IoC容器放入到application对象以前进行了IoC容器的配置和刷新操做,调用了configureAndRefreshWebApplicationContext()方法,该方法源码以下:jsp
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } } wac.setServletContext(sc); /* CONFIG_LOCATION_PARAM = "contextConfigLocation" 获取web.xml中<context-param>标签配置的全局变量,其中key为CONFIG_LOCATION_PARAM 也就是咱们配置的相应Bean的xml文件名,并将其放入到WebApplicationContext中 */ String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } customizeContext(sc, wac); wac.refresh(); }
比较重要的就是获取到了web.xml中的<context-param>标签配置的全局变量contextConfigLocation,并最后一行调用了refresh()方法,ConfigurableWebApplicationContext是一个接口,经过对经常使用实现类ClassPathXmlApplicationContext逐层查找后能够找到一个抽象类AbstractApplicationContext实现了refresh()方法,其源码以下:ide
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
该方法主要用于建立并初始化contextConfigLocation类配置的xml文件中的Bean,所以,若是咱们在配置Bean时出错,在Web应用启动时就会抛出异常,而不是等到运行时才抛出异常。
整个ContextLoaderListener类的启动过程到此就结束了,能够发现,建立ContextLoaderListener是比较核心的一个步骤,主要工做就是为了建立根IoC容器并使用特定的key将其放入到application对象中,供整个Web应用使用,因为在ContextLoaderListener类中构造的根IoC容器配置的Bean是全局共享的,所以,在<context-param>标识的contextConfigLocation的xml配置文件通常包括:数据库DataSource、DAO层、Service层、事务等相关Bean。
在监听器listener初始化完成后,按照文章开始的讲解,接下来会进行filter的初始化操做,filter的建立和初始化中没有涉及IoC容器的相关操做,所以不是本文讲解的重点,本文举例的filter是一个用于编码用户请求和响应的过滤器,采用utf-8编码用于适配中文。
Servlet的初始化过程能够经过一张图来总结,以下所示:
经过类图和相关初始化函数调用的逻辑来看,DispatcherServlet类的初始化过程将模板方法使用的淋漓尽致,其父类完成不一样的统一的工做,并预留出相关方法用于子类覆盖去完成不一样的可变工做。
DispatcherServelt类的本质是Servlet,经过文章开始的讲解可知,在Web应用部署到容器后进行Servlet初始化时会调用相关的init(ServletConfig)方法,所以,DispatchServlet类的初始化过程也由该方法开始。上述调用逻辑中比较重要的就是FrameworkServlet抽象类中的initServletBean()方法、initWebApplicationContext()方法以及DispatcherServlet类中的onRefresh()方法,接下来会逐一进行讲解。
首先来看initServletBean()方法:
@Override protected final void initServletBean() throws ServletException { getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'"); if (this.logger.isInfoEnabled()) { this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started"); } long startTime = System.currentTimeMillis(); try { //这里是重点,用于初始化子ApplicationContext对象,主要是用来加载<servlet/>对应的servletName-servlet.xml文件如:springMVC_rest-servlet.xml this.webApplicationContext = initWebApplicationContext(); initFrameworkServlet(); } catch (ServletException ex) { this.logger.error("Context initialization failed", ex); throw ex; } catch (RuntimeException ex) { this.logger.error("Context initialization failed", ex); throw ex; } if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " + elapsedTime + " ms"); } }
接下来来着重分析initWebApplicationContext()方法,
protected WebApplicationContext initWebApplicationContext() { /* 获取由ContextLoaderListener建立的根IoC容器 获取根IoC容器有两种方法,还可经过key直接获取 */ WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = null; if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> set // the root application context (if any; may be null) as the parent /* 若是当前Servelt存在一个WebApplicationContext即子IoC容器 而且上文获取的根IoC容器存在,则将根IoC容器做为子IoC容器的父容器 */ cwac.setParent(rootContext); } //配置并刷新当前的子IoC容器,功能与前文讲解根IoC容器时的配置刷新一致,用于构建相关Bean configureAndRefreshWebApplicationContext(cwac); } } } if (wac == null) { // No context instance was injected at construction time -> see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id //若是当前Servlet不存在一个子IoC容器则去查找一下 wac = findWebApplicationContext(); } if (wac == null) { // No context instance is defined for this servlet -> create a local one //若是仍旧没有查找到子IoC容器则建立一个子IoC容器 wac = createWebApplicationContext(rootContext); } if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -> trigger initial onRefresh manually here. //调用子类覆盖的onRefresh方法完成“可变”的初始化过程 onRefresh(wac); } if (this.publishContext) { // Publish the context as a servlet context attribute. String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); if (this.logger.isDebugEnabled()) { this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]"); } } return wac; }
经过函数名不难发现,该方法的主要做用一样是建立一个WebApplicationContext对象,即Ioc容器,不过前文讲过每一个Web应用最多只能存在一个根IoC容器,这里建立的则是特定Servlet拥有的子IoC容器,可能有些读者会有疑问,为何须要多个Ioc容器,首先介绍一个父子IoC容器的访问特性,有兴趣的读者能够自行实验。
在学习Spring时,咱们都是从读取xml配置文件来构造IoC容器,经常使用的类有ClassPathXmlApplicationContext类,该类存在一个初始化方法用于传入xml文件路径以及一个父容器,咱们能够建立两个不一样的xml配置文件并实现以下代码:
//applicationContext1.xml文件中配置一个id为baseBean的Bean ApplicationContext baseContext = new ClassPathXmlApplicationContext("applicationContext1.xml"); Object obj1 = baseContext.getBean("baseBean"); System.out.println("baseContext Get Bean " + obj1); //applicationContext2.xml文件中配置一个id未subBean的Bean ApplicationContext subContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext2.xml"}, baseContext); Object obj2 = subContext.getBean("baseBean"); System.out.println("subContext get baseContext Bean " + obj2); Object obj3 = subContext.getBean("subBean"); System.out.println("subContext get subContext Bean " + obj3); //抛出NoSuchBeanDefinitionException异常 Object obj4 = baseContext.getBean("subBean"); System.out.println("baseContext get subContext Bean " + obj4);
首先建立baseContext没有为其设置父容器,接着能够成功获取id为baseBean的Bean,接着建立subContext并将baseContext设置为其父容器,subContext能够成功获取baseBean以及subBean,最后试图使用baseContext去获取subContext中定义的subBean,此时会抛出异常NoSuchBeanDefinitionException,因而可知,父子容器相似于类的继承关系,子类能够访问父类中的成员变量,而父类不可访问子类的成员变量,一样的,子容器能够访问父容器中定义的Bean,但父容器没法访问子容器定义的Bean。
经过上述实验咱们能够理解为什么须要建立多个Ioc容器,根IoC容器作为全局共享的IoC容器放入Web应用须要共享的Bean,而子IoC容器根据需求的不一样,放入不一样的Bean,这样可以作到隔离,保证系统的安全性。
接下来继续讲解DispatcherServlet类的子IoC容器建立过程,若是当前Servlet存在一个IoC容器则为其设置根IoC容器做为其父类,并配置刷新该容器,用于构造其定义的Bean,这里的方法与前文讲述的根IoC容器相似,一样会读取用户在web.xml中配置的<servlet>中的<init-param>值,用于查找相关的xml配置文件用于构造定义的Bean,这里再也不赘述了。若是当前Servlet不存在一个子IoC容器就去查找一个,若是仍然没有查找到则调用
createWebApplicationContext()方法去建立一个,查看该方法的源码以下图所示:
该方法用于建立一个子IoC容器并将根IoC容器作为其父容器,接着进行配置和刷新操做用于构造相关的Bean。至此,根IoC容器以及相关Servlet的子IoC容器已经配置完成,子容器中管理的Bean通常只被该Servlet使用,所以,其中管理的Bean通常是“局部”的,如SpringMVC中须要的各类重要组件,包括Controller、Interceptor、Converter、ExceptionResolver等。相关关系以下图所示:
当IoC子容器构造完成后调用了onRefresh()方法,该方法的调用与initServletBean()方法的调用相同,由父类调用但具体实现由子类覆盖,调用onRefresh()方法时将前文建立的IoC子容器做为参数传入,查看DispatcherServletBean类的onRefresh()方法源码以下:
@Override protected void onRefresh(ApplicationContext context) { initStrategies(context); } /** * 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); }
onRefresh()方法直接调用了initStrategies()方法,源码如上,经过函数名能够判断,该方法用于初始化建立multipartResovle来支持图片等文件的上传、本地化解析器、主题解析器、HandlerMapping处理器映射器、HandlerAdapter处理器适配器、异常解析器、视图解析器、flashMap管理器等,这些组件都是SpringMVC开发中的重要组件,相关组件的初始化建立过程均在此完成。因为篇幅问题本文再也不进行更深刻的探讨,有兴趣的读者能够阅读本系列文章的其余博客内容。至此,DispatcherServlet类的建立和初始化过程也就结束了,整个Web应用部署到容器后的初始化启动过程的重要部分所有分析清楚了,经过前文的分析咱们能够认识到层次化设计的优势,以及IoC容器的继承关系所表现的隔离性。分析源码能让咱们更清楚的理解和认识到相关初始化逻辑以及配置文件的配置原理。