Backend Development 11 min read

Spring MVC Web Configuration and Context Initialization Process

This article explains how Spring MVC integrates web capabilities by configuring web.xml, initializing the root WebApplicationContext via ContextLoaderListener, creating a child context for DispatcherServlet, and managing the hierarchical relationship between the two contexts to share beans across a Java web application.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Spring MVC Web Configuration and Context Initialization Process

Spring MVC extends the core Spring Framework with web capabilities by using WebApplicationContext , which is created and managed through ContextLoaderListener and DispatcherServlet within a web container such as Tomcat.

Four main configurations are required in web.xml : servlet definition for DispatcherServlet, servlet-specific configuration file, contextConfigLocation initialization parameter, and the ContextLoaderListener .

The root context (ROOT WebApplicationContext ) is initialized by ContextLoaderListener using the configuration file specified by contextConfigLocation . The listener ensures only one root context exists, logs initialization steps, and stores the context in the ServletContext under the attribute WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE .

DispatcherServlet then creates its own child WebApplicationContext . During its initWebApplicationContext() method, it retrieves the parent root context, creates a local context (default XmlWebApplicationContext ), sets the parent, refreshes it, and publishes it as a servlet attribute.

The hierarchical relationship allows beans defined in the root context (e.g., DAO, Service) to be accessible to the DispatcherServlet’s context, while servlet‑specific beans (e.g., Controllers, ViewResolvers) remain scoped to the child context.

Code examples illustrate the key methods in ContextLoader and FrameworkServlet that perform these steps.

JavaBackend DevelopmentSpring MVCDispatcherServletContextLoaderListenerWebApplicationContext
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.