Spring 核心监听器 ContextLoaderListener

ServletContext 保存着 WebApplicationContext

  • ServletContext 以 类似 Map 的形式保存了 WebApplicationContext

因此通过指定的 key , 可以获得 Spring 的工厂 WebApplicationContext

说明

  • WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 就是 ServletContext 中 保存 WebApplicationContext 的key。
  • Spring 提供的 WebApplicationContextUtils 类,已经实现获得 WebApplicationContext 逻辑

ServletContext 是怎么保存 WebApplicationContext 的?

ContextLoader

ContextLoader是把WebApplicationContextXmlWebApplicationContext 是默认实现类)放在了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 中。

猜你喜欢

转载自blog.csdn.net/ai_shuyingzhixia/article/details/81533139