详解 Spring 中 ContextLoaderListener 的作用
最近公司来了新同事,刚毕业不久。问到我 web.xml 中的 ContextLoaderListener 是干什么用的?我一时愣住了,因为我也不清楚了。关于 ContextLoaderListener 的知识,我们这里一起再认识一下!
所谓ContextLoaderListener,就是在web部署描述符即web.xml里面经常配置的一个监听器,如下:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener 可以不配置吗
答案是肯定的:可以不做任何配置!
查看了ContextLoaderListener 源代码,发现它继承自ContextLoader,并且实现ServletContextListener接口。ContextLoaderListener 源代码很简单,核心是实现了 ServletContextListener 的contextInitialized和contextDestroyed方法
我们看下类图结构,只列出一部分属性和方法
ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。至于ApplicationContext.xml这个配置文件部署在哪,如何配置多个xml文件,书上都没怎么详细说明。现在的方法就是查看它的API文档。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。它的API说明如下:
第一段说明ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它实现了HttpServlet这个接口。
第二段,ContextLoader创建的是 XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->BeanFactory这样一来spring中的所有bean都由这个类来创建
第三段,讲如何部署applicationContext的xml文件。 如果在web.xml中不写任何参数配置信息,默认的路径是/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml; 如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext-*.xml
</param-value>
</context-param>
在
由此可见applicationContext.xml的文件位置就可以有两种默认实现:
第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener;
第二种:将之放到classpath下,但是此时要在web.xml中加入
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
</context-param>
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/04/16 09:20