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