15

我是 Spring MVC 世界的新手。今天我正在研究 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 项目中没有使用和标签,因为如果我删除这些标签,projext 仍然运行良好....对吗?

4

1 回答 1

35

ContextLoaderListener是一个启动 Spring 容器的类。基本上每个 Spring 应用程序都由几个 bean 和布线组成(对哪些 bean 相互依赖的声明性描述)。这个描述在历史上是用 XML 编写的(现在我们有注解、Java 配置、CLASSPATH 扫描等)

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

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

于 2012-11-30T18:18:58.317 回答