1. 程式人生 > >精盡Spring MVC原始碼分析 - WebApplicationContext 容器的初始化

精盡Spring MVC原始碼分析 - WebApplicationContext 容器的初始化

> 該系列文件是本人在學習 Spring MVC 的原始碼過程中總結下來的,可能對讀者不太友好,請結合我的原始碼註釋 [Spring MVC 原始碼分析 GitHub 地址](https://github.com/liu844869663/spring-framework) 進行閱讀 > > Spring 版本:5.2.4.RELEASE 隨著 `Spring Boot` 和 `Spring Cloud` 在許多中大型企業中被普及,可能你已經忘記當年經典的 Servlet + Spring MVC 的組合,是否還記得那個 `web.xml` 配置檔案。在開始本文之前,請先拋開 `Spring Boot` 到一旁,回到從前,一起來看看 Servlet 是怎麼和 Spring MVC 整合,怎麼來初始化 Spring 容器的,在開始閱讀本文之前,最好有一定的 Servlet 和 Spring IOC 容器方面的知識,比較容易理解 ### 概述 在開始看具體的原始碼實現之前,我們先一起來看看現在“陌生”的 `web.xml` 檔案,可以檢視我的另一篇 [MyBatis 使用手冊](https://www.cnblogs.com/lifullmoon/p/14014660.html) 文件中**整合 Spring**小節涉及到的 `web.xml` 的檔案,部分內容如下: ```xml
Archetype Created Web Application org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:spring-mybatis.xml SpringMVC org.springframework.web.servlet.DispatcherServlet
contextConfigLocation classpath:spring-mvc.xml 1
true
SpringMVC /
``` `【1】` 處,配置了 `org.springframework.web.context.ContextLoaderListener` 物件,它實現了 Servlet 的 `javax.servlet.ServletContextListener` 介面,能夠監聽 ServletContext 物件的生命週期,也就是監聽 Web 應用的生命週期,當 Servlet 容器啟動或者銷燬時,會觸發相應的 ServletContextEvent 事件,ContextLoaderListener 監聽到啟動事件,則會初始化一個**Root** Spring WebApplicationContext 容器,監聽到銷燬事件,則會銷燬該容器 `【2】` 處,配置了 `org.springframework.web.servlet.DispatcherServlet` 物件,它繼承了 `javax.servlet.http.HttpServlet` 抽象類,也就是一個 Servlet。Spring MVC 的核心類,處理請求,會初始化一個**屬於它**的 Spring WebApplicationContext 容器,並且這個容器是以 `【1】` 處的 Root 容器作為父容器 - 為什麼有了 `【2】` 建立了容器,還需要 `【1】` 建立 Root 容器呢?因為可以配置多個 `【2】` 呀,當然,實際場景下,不太會配置多個 `【2】`