Spring來一發(一)Spring容器
1、容器啟動
Spring提供了構建Web應用程式的元件Spring MVC,通過Spring MVC和Spring Core就可以搭建一個穩定的JavaWeb專案。以下介紹Spring容器的啟動過程。
Tomcat伺服器啟動入口檔案是web.xml,通過在其中配置相關的Listener和Servlet即可載入Spring MVC所需資料。
<!-- 載入Spring配置檔案 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 載入spring mvc --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
ContextLoaderListener基於Web上下文級別的監聽器在啟動伺服器時就建立ApplicationContext並且將配置的Spring Bean載入到容器中。
DispatcherServlet是一個請求分發控制器,所有匹配的URL都會通過該Servlet分發執行,在建立Servlet物件時會初始化Spring MVC相關配置。
二、ContextLoaderListener
web容器提供了一個全域性的上下文環境ServletContext,為後面Spring容器提供宿主環境,在web容器啟動時會觸發容器初始化事件,ContextLoaderListener監聽到這個事件後其contextInitialized方法就會被呼叫,在這個方法中,spring會初始化一個根上下文,也就是WebApplicationContext,實際實現類一般是XmlWebApplicationContext,這個其實就是spring的IoC容器,Spring會將它儲存到ServletContext,可供後面獲取到該容器中的bean。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public ContextLoaderListener() { } public ContextLoaderListener(WebApplicationContext context) { super(context); } public void contextInitialized(ServletContextEvent event) { this.initWebApplicationContext(event.getServletContext()); } public void contextDestroyed(ServletContextEvent event) { this.closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
ContextLoaderListener原始碼如上,一個構造方法,一個初始化方法contextInitialized,和一個銷燬方法contextDestroyed。initWebApplicationContext方法做了三件事:建立WebApplicationContext;載入對應的Spring檔案建立裡面的Bean例項;將WebApplicationContext放入ServletContext(就是Java Web的全域性變數)中。
三、DispatcherServlet
在contextLoaderListener監聽器初始化完畢後,開始初始化web.xml中配置的Servlet,這個servlet可以配置多個,以DispatcherServlet為例,這個servlet實際上是一個標準的前端控制器,用以轉發、處理每個servlet請求。DispatcherServlet在初始化的時候會建立自己的IoC上下文,用以持有Spring MVC相關的Bean。在建立DispatcherServlet自己的IoC上下文時,會先從ServletContext中獲取根上下文WebApplicationContext作為自己的parent上下文。
DispatcherServlet的上下文僅僅是Spring MVC的上下文, 而ContextLoaderListener的上下文則對整個Spring都有效。ContextLoaderListener中建立ApplicationContext主要用於整個Web應用程式需要共享的一些元件,比如DAO的ConnectionFactory等。而由DispatcherServlet建立的ApplicationContext主要用於和該Servlet相關的一些元件,比如Controller、ViewResovler等。
參考資料: