一、為何需要關注IOC容器啟動?
在Java Web開發中,Spring MVC框架的基石正是IOC容器。但你是否思考過:獨立的IOC模塊如何與Tomcat等Servlet容器協同工作??其啟動過程與Web容器的生命周期深度綁定,這是構建穩定Spring應用的關鍵前提。
二、兩種配置方式的核心邏輯
1. 傳統web.xml配置解析
通過DispatcherServlet
和ContextLoaderListener
這對黃金組合實現容器初始化:
<!-- 根容器配置 -->
<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener><!-- MVC容器配置 -->
<servlet><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/app-context.xml</param-value></init-param>
</servlet>
關鍵機制:
ContextLoaderListener
初始化父容器(根上下文)DispatcherServlet
創建子容器并關聯父容器通過
ServletContext
實現容器間通信
2. Servlet 3.0+ 注解配置
更簡潔的Java配置實現等效功能:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{RootConfig.class}; // 根容器配置}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{WebConfig.class}; // MVC容器配置}
}
三、啟動流程源碼深度拆解
1. 容器初始化入口:ContextLoaderListener
public class ContextLoaderListener implements ServletContextListener {public void contextInitialized(ServletContextEvent event) {initWebApplicationContext(event.getServletContext()); // 啟動核心入口}
}
核心作用:
監聽Servlet容器啟動事件
觸發根容器的創建與初始化
2. 容器創建引擎:ContextLoader
public WebApplicationContext initWebApplicationContext(ServletContext sc) {// 1. 創建XmlWebApplicationContext實例if (this.context == null) {this.context = createWebApplicationContext(sc);}// 2. 配置容器環境configureAndRefreshWebApplicationContext(wac, sc);
}
關鍵步驟:
從
contextConfigLocation
加載Bean定義將Servlet參數注入容器環境
調用
refresh()
完成容器初始化
四、Web容器上下文設計精要
1. 層次化容器體系
2. WebApplicationContext核心能力
public interface WebApplicationContext extends ApplicationContext {String SCOPE_REQUEST = "request"; ?// 請求作用域String SCOPE_SESSION = "session"; // 會話作用域ServletContext getServletContext(); // 獲取Web容器上下文
}
五、技術實踐建議
通過源碼分析,我們驗證了三個核心結論:
容器啟動:由
ContextLoaderListener
監聽Web服務器啟動觸發容器刷新:
refresh()
方法包含12個關鍵初始化步驟容器交互:子容器通過
getParentBeanFactory()
委托父容器查找Bean
延伸學習建議:
若想深入理解
XmlWebApplicationContext
如何加載WEB-INF下的配置文件,可參考:https://pan.quark.cn/s/7c24f4650a5b該課程通過20+核心源碼案例,演示了BeanDefinition加載、環境配置等關鍵過程。
本文技術要點導圖
(注:文中技術解析基于Spring 5.3.x源碼實現,適用于Tomcat/Jetty等Servlet容器)