Spring的监听器ContextLoaderListener

一、作用

ContextLoaderListener监听器的作用就是启动web容器时,自动装配ApplicationContext的配置信息。它实现了ServletContextListener接口,在web.xml文件中配置这个监听器,启动容器时,就会默认执行它实现的方法。

二、ContextLoader

ContextLoaderListener关联了ContextLoader,整个加载配置过程也是由ContextLoader来完成的。

1. ContextLoader可以由ContextLoaderListener和ContextLoaderServlet生成。ContextLoaderServlet不仅继承了ContextLoader,而且也实现了HttpServlet方法。

2. ContextLoader创建了WebApplicationContext,它继承了ApplicationContext —> BeanFactory,说明Spring的所有bean也是在ContextLoader中创建的。

三、如何配置applicationContext.xml文件

1. 采用默认配置路径。将applicationContext.xml放置在WEB-INF下,不能自定义文件名。然后只需在web.xml中配置。

<!-- Spring Listener -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2. 指定配置文件。需要在web.xml中配置参数指定文件路径。然后仍需配置上面代码中的监听器。

<!-- 参 数:Spring配置路径 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

四、扩展

如果有多个xml文件,可以写在一起并用","号分隔。也可以采用通配符的形式,applicationContext-*.xml,符合条件的文件都会被一同加载。

原文地址:https://www.cnblogs.com/libra0920/p/6163632.html