有关Spring web.xml <context-param>和<listener>标记的一些信息(参考Hello World示例)

And*_*ili 14 java spring web.xml spring-mvc

我是Spring MVC World的新手.今天我正在研究STS生成的简单"Hello World"示例:File ---> Spring Template Project ---> Spring MVC Project

在web.xml中,我有DispatcherServlet的声明和由它处理的请求映射......到这里一切都好

在web.xml中我也有这部分代码:

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

阅读关于ContextLoaderListener的Spring文档我读到这个类执行监听器的bootstrap来启动Spring的根WebApplicationContext但是......它到底意味着什么?

另一个疑问是关于我传递给我的上下文的contextConfigLocation参数......究竟是什么?打开/WEB-INF/spring/root-context.xml文件似乎它不包含任何配置......它是由我的模板项目创建过程自动创建的void配置文件吗?Spring项目中应该包含哪种配置?

我认为这个和Hello标签没有在这个Hello World项目中使用,因为如果我删除这些标签,那么projext仍然运行良好....是不是?

Tom*_*icz 35

ContextLoaderListener是一个启动Spring容器的类.基本上每个Spring应用程序都包含几个bean和接线(哪些bean相互依赖的声明性描述).这个描述在历史上用XML编写(现在我们有注释,Java配置,CLASSPATH扫描等)

没有Spring容器,bean只是Java类,而Spring配置文件只是一个无用的XML文档.ContextLoaderListener读取该文件,查找您的类,实例化它们和连线.然后将所有豆子放在容器中.

另外,ContextLoaderListener在应用程序关闭时关闭上下文(如果需要清理,则关闭所有bean).