一、为何需要关注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 {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class}; // 根容器配置
}
@Override
protected 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容器)