Spring中的DispatcherServlet和ContextLoaderListener

9
Spring框架中的DispatcherServletContextLoaderListener有什么区别?在使用Spring框架时,我们需要在web.xml中同时配置它们吗?
3个回答

20
据我所知,每个DispatcherServlet都会有一个WebApplicationContext。默认情况下,DispatcherServlet会在WEB-INF文件夹下查找名为[appname]-servlet.xml的Spring配置文件。

我们需要配置DispatcherServlet吗?

是的,每个Spring应用程序都应该配置DispatcherServlet,因为所有请求都通过它路由。它决定控制器类处理请求的适当方法。一旦控制器返回model和逻辑视图,DispatcherServlet将借助ViewResolver解析视图(通常是JSP),并将model数据传递给视图,最终在浏览器上呈现。

我们需要配置ContextLoaderListener吗?

不需要,这不是强制性的。Spring应用程序可以没有ContextLoaderListener

为什么我们需要ContextLoaderListener

通常,在构建多层应用程序时,我们不希望在一个配置文件[appname]-servlet.xml中混杂所有bean。例如,如果您配置了spring security,则需要在security-context.xml中包含所有这些bean,同样,属于服务层的所有bean都配置在applicationContext.xml中,有些人希望在dao-context.xml中配置属于DAO层的bean。因此,当您在不同的上下文文件中配置所有这些bean时,需要让Spring知道这些文件存在,因为Spring只知道[appname]-servlet.xmlContextLoaderListener将帮助Spring识别所有其他上下文文件。
希望对您有所帮助!

1
这应该是被接受的答案。你解释得非常清楚。谢谢! - LppEdd
1
我没有很好地理解被接受的答案。这个答案的简单性使得ContextLoaderListener的目的以及DispatcherServlet的作用非常清晰。很棒的解释,谢谢。 - Aniket

4
根WebApplicationContext是整个应用程序共享的Spring应用程序上下文。
DispatcherServlet实例实际上有自己的WebApplicationContext。
在一个应用程序中可以有多个DispatcherServlet实例,每个实例都有自己的WebApplicationContext。
根WebApplicationContext在整个应用程序中是共享的,因此如果您有一个根WebApplicationContext和多个DispatcherServlet,则DispatcherServlet将共享根WebApplicationContext。
但是,对于一个简单的Spring MVC应用程序,甚至可以出现不需要有根WebApplicationContext的情况。 DispatcherServlet仍然会有自己的WebApplicationContext,但它实际上不需要有父级根WebApplicationContext。
那么,哪些bean应该放在根Web Application Context中,哪些bean应该放在DispatcherServlet的Web Application Context中呢? 好吧,一般的bean,如服务和DAO,在根Web Application Context中,而更具有Web特定性的bean,如控制器,则包括在DispatcherServlet的Web Application Context中。

0

当DispatcherServlet启动时,它创建了一个Spring应用程序上下文并开始使用在配置文件或给定的类中声明的bean进行加载。但是,在Spring Web应用程序中,通常还有另一个应用程序上下文。这个其他应用程序上下文是由ContextLoaderListener创建的。

而DispatcherServlet被期望加载包含Web组件(例如控制器、视图解析器和处理程序映射)的bean,ContextLoaderListener则被期望加载应用程序中的其他bean。这些bean通常是驱动应用程序后端的中间层和数据层组件。

祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接