ServletContext 保存着 WebApplicationContext
ServletContext
以 类似Map
的形式保存了WebApplicationContext
因此通过指定的 key
, 可以获得 Spring 的工厂 WebApplicationContext
。
说明
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
就是ServletContext
中 保存WebApplicationContext
的key。- Spring 提供的
WebApplicationContextUtils
类,已经实现获得WebApplicationContext
逻辑
ServletContext 是怎么保存 WebApplicationContext 的?
ContextLoader
ContextLoader
是把WebApplicationContext
(XmlWebApplicationContext 是默认实现类)放在了ServletContext
中
ContextLoaderListener
配置
在 web.xml
文件中配置 Spring的核心监听器 ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
原理 与 作用
- 初始化
WebApplicationContext
,
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
其中,ContextLoaderListener的方法 contextInitialized()
, 默认由父类 ContextLoader的 initWebApplicationContext
(初始化web应用上下文) 方法中实现。
initWebApplicationContext()
方法中,创建IOC容器并存到 servletContext 中。