ContextLoaderListener监听器的作用就是启动web容器时,自动装配ApplicationContext的配置信息。它实现了ServletContextListener接口,在web.xml文件中配置这个监听器,Tomcat或Jetty启动容器时,就会默认执行它实现的方法。
<!-- 配置spring IOC参数路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-context*.xml</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
通过扩展ContextLoaderListener类,可以增加初始化时的个性化功能,如输出产品的信息等。
在org.springframework.web.context.ContextLoader中有一个静态属性,
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
默认的DEFAULT_STRATEGIES_PATH=ContextLoader.properties,路径在ContextLoader类的同一级目录下,都在spring-web-..*.RELEASE.jar包内。ContextLoader.properties的内容为:
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
实际的实例化为org.springframework.web.context.support.XmlWebApplicationContext。