tomcat服務器啓動入口文件是web.xml,經過在其中配置相關的Listener和servlet便可加載Spring MVC所需數據。基於Spring MVC最簡單的配置以下。java
<!-- 加載Spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-context*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加載spring mvc --> <servlet> <servlet-name>spring3mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-mvc*.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring3mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
ContextLoaderListener基於Web上下文級別的監聽器在啓動服務器時就建立ApplicationContext而且將配置的Spring Bean加載到容器裏面。web
DispatcherServlet是一個請求分發器,全部匹配的URL都會都會經過該Servlet分發執行,在建立Servlet對象時會初始化Spring MVC相關配置。spring
在web.xml中,咱們看到基於ContextLoaderListener和DispatcherServlet均可以配置spring相關的xml,可是兩種方式加載spring的ApplicationContext上下文對象並非合併存儲的。因此建議,基於mvc相關的spring配置由DispatcherServlet加載,而其餘的JavaBean則由ContextLoaderListener加載。spring-mvc
一.ContextLoaderListenertomcat
ContextLoaderListener是一個實現了ServletContextListener接口的監聽器,在啓動項目時會觸發contextInitialized方法(該方法主要完成ApplicationContext對象的建立),在關閉項目時會觸發contextDestroyed方法(該方法會執行ApplicationContext清理操做)。服務器
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
ContextLoaderListener加載Spring上下文的過程能夠用如下圖表示,黃色區域是核心代碼區。mvc
簡單介紹一下上圖的運行流程:app
1.啓動項目時觸發contextInitialized方法,該方法就作一件事:經過父類ContextLoad的initWebApplicationContext方法建立Spring上下文對象。url
2.initWebApplicationContext方法作了三件事情,建立WebApplicationContext;加載對應spring配置文件裏建立的bean實例,將WebApplicationContext方法放入ServletContext中(java Web的全局變量)中。spa
3.createWebApplicationContext建立上下文對象,支持用戶自定義上下文對象,但必須繼承自ConfigurableWebApplicationContext,而Spring MVC默認使用XmlWebApplicationContext做爲ApplicationContext(它僅僅是一個接口)的實現。
4. configureAndRefreshWebApplicationContext方法用於封裝ApplicationContext數據而且初始化全部相關Bean對象,它會從web.xml中讀取取名爲contextConfigLocation的配置,這就是spring xml數據源設置,而後放到ApplicationContext中,最後調用refresh方法執行全部java對象的建立。
5.完成ApplicationContext建立後就是將其放入ServletContext中,注意它存儲的key值常量。