DispatcherServlet and ContextLoaderListener in Spring

AFAIK each DispatcherServlet will have a WebApplicationContext. By default the DispatcherServlet looks for a spring configuration file named [appname]-servlet.xml under WEB-INF folder.

Do we need to configure DispatcherServlet?

Yes, every spring application should configure DispatcherServlet as it is the one through which all the requests are routed. It decides the appropriate method of the controller class to handle the request. Once controller returns the model along with the logical view, DispatcherServlet takes the help of ViewResolver to resolve the view (generally JSPs) and will pass the model data to the view, which is finally rendered on the browser.

Do we need to configure ContextLoaderListener?

No, this is not mandatory. Spring applications can live with out ContextLoaderListener.

Why do we need ContextLoaderListener?

Usually when we build multi-tier applications we don't want to clutter all the beans in one config file [appname]-servlet.xml. For example if you configure spring security you wanted to include all those beans in security-context.xml, in the same way all the beans belonging to service layer are configured in applicationContext.xml and some would like to configure beans belonging to DAO layer in dao-context.xml. So when you configure all these beans in different context files, you need to let know spring that these files exist as spring only knows about [appname]-servlet.xml. ContextLoaderListener will help spring recognize all the other context files.

Hope this helps!


The root WebApplicationContext is a Spring Application Context shared across the application.

A DispatcherServlet instance actually has its own WebApplicationContext.

One can have multiple DispatcherServlet instances in an application, and each will have its own WebApplicationContext.

The root WebApplicationContext is shared across the application, so if you have a root WebApplicationContext and multiple DispatcherServlets, the DispatcherServlets will share the root WebApplicationContext.

However, for a simple Spring MVC application, one can even have a situation where there is no need to have a root WebApplicationContext. A DispatcherServlet would still have its own WebApplicationContext, but it doesn’t actually need to have a parent root WebApplicationContext.

So, which beans should go in the root Web Application Context and which beans should go in the DispatcherServlet’s Web Application Context? Well, general beans such as services and DAOs make their way in root Web Application Context, and more web-specific beans such as controllers are included in DispatcherServlet’s Web Application Context.