有关Spring web.xml的一些信息 和 标签(参考Hello World示例)


问题内容

我在Spring MVC World上还很陌生。今天,我研究由STS生成的简单“ Hello World”示例:文件—> Spring模板项目—>
Spring MVC项目

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

阅读有关ContextLoaderListener的Spring文档,我读到该类执行侦听器的引导程序以启动Spring的根WebApplicationContext,但是…这到底意味着什么?

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

我认为在此Hello World项目中未使用tath和标签,因为如果删除这些标签,projext仍然可以很好地运行..对吗?


问题答案:

ContextLoaderListener是启动Spring容器的类。基本上,每个Spring应用程序都由几个bean和连线组成(有关哪些bean相互依赖的说明性描述)。此描述以前是用XML编写的(如今,我们有了注释,Java配置,CLASSPATH扫描等)。

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

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