ContextLoaderListener 简介

ContextLoaderListener 是 Spring 框架中的一个监听器,它可以在 web 应用启动时,自动加载一个或多个 Spring 配置文件,并将其中定义的 bean 实例化,从而构建 Spring 容器,并保证 Spring 容器在整个 web 应用中只有一个实例。

ContextLoaderListener 原理

ContextLoaderListener 实现原理很简单,当 web 应用启动时,容器会自动加载 web.xml 文件,web.xml 文件中配置了 ContextLoaderListener,容器会自动调用 ContextLoaderListener 的 contextInitialized() 方法,contextInitialized() 方法会加载 Spring 的配置文件,并将其中定义的 bean 实例化,构建 Spring 容器,从而保证 Spring 容器在整个 web 应用中只有一个实例。

ContextLoaderListener 使用

ContextLoaderListener 使用非常简单,只需要在 web.xml 中配置 ContextLoaderListener,并配置 Spring 配置文件的路径,如下所示:

123456
XML

<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>

contextConfigLocation 参数用于指定 Spring 配置文件的路径,listener-class 参数指定 ContextLoaderListener 的全限定名,只有配置了 ContextLoaderListener,web 应用启动时,才会自动加载 Spring 配置文件,从而构建 Spring 容器。