Programming
What is the difference between ApplicationContext and WebApplicationContext in Spring MVC
Navigating the foundational elements of the Spring Framework is crucial for any developer aiming to master robust application development. Two terms that frequently arise and often cause confusion are ApplicationContext and WebApplicationContext. While both serve as core Inversion of Control (IoC) containers responsible for managing beans, their specific roles and capabilities differ significantly, particularly within the context of a web application. Understanding the difference between ApplicationContext and WebApplicationContext in Spring MVC is fundamental for designing scalable and maintainable web services. This distinction isn’t merely academic; it dictates how your beans are managed, how resources are accessed, and ultimately, how your Spring application behaves in a web environment versus a standalone one.
Understanding the Spring ApplicationContext
At its core, the Spring ApplicationContext is the central interface within a Spring application for providing configuration information to the framework. It’s an advanced form of the BeanFactory, offering more enterprise-specific functionalities such as message source handling, event publication, and resource loading. Essentially, it’s the heart of the Spring IoC container, responsible for instantiating, configuring, and assembling beans by reading configuration metadata, typically from XML, Java annotations, or Java code.
In non-web applications, such as standalone console applications, batch jobs, or desktop applications, you would typically initialize an ApplicationContext directly. For instance, a ClassPathXmlApplicationContext or AnnotationConfigApplicationContext can be used to load bean definitions from a classpath XML file or Java configuration classes, respectively. This context then manages the entire lifecycle of your application’s beans, from creation to destruction, ensuring that dependencies are correctly injected and services are readily available. This makes the Spring IoC container incredibly powerful for managing complex object graphs.
Consider a simple command-line tool that processes data. An ApplicationContext would manage the data source, service beans, and data access objects (DAOs). Its lifecycle is tied to the application’s runtime; once the application finishes its task, the context is closed. This provides a clean separation of concerns and facilitates modular development, allowing components to be easily swapped or reconfigured without altering the core application logic.
Diving into WebApplicationContext
The WebApplicationContext is a specialized extension of the standard ApplicationContext designed specifically for web applications. Unlike its general-purpose counterpart, it understands web-specific concepts and integrates seamlessly with the web environment, primarily through the Servlet API. When you build a Spring MVC application, the DispatcherServlet typically initializes its own WebApplicationContext. This context is aware of the ServletContext, which provides access to web resources and parameters specific to the web application.
This web-aware context provides crucial features necessary for web development, such as support for web-specific scopes like request, session, and application. Beans defined within a WebApplicationContext can have their lifecycle tied to these web scopes, which is essential for managing state across HTTP requests or user sessions. For instance, a bean annotated with @RequestScope will have a new instance created for each incoming HTTP request, ensuring isolated data handling for every interaction.
The initialization of a WebApplicationContext is typically handled by the Spring DispatcherServlet (or ContextLoaderListener for the root context). This process is integral to how Spring MVC handles incoming requests, mapping them to controllers, and rendering views. As noted by Spring’s official documentation, “The WebApplicationContext is an extension of the ApplicationContext that has the necessary features for web applications.” This emphasizes its specialized role in handling the complexities of web environments, making it indispensable for any Spring-powered web application. You can explore more about its setup and configuration in the Spring Framework Reference Documentation.
The Hierarchical Relationship: Parent-Child Contexts
One of the most powerful aspects of Spring’s context management in web applications is the parent-child hierarchy between ApplicationContext and WebApplicationContext instances. In a typical Spring MVC setup, there are often two contexts: a root ApplicationContext and one or more WebApplicationContext instances. The root ApplicationContext is usually loaded by the ContextLoaderListener in web.xml and contains beans common to the entire application, such as service layers, data access objects, and infrastructure components. This context acts as the parent.
Each DispatcherServlet in your application then initializes its own WebApplicationContext, which becomes a child of the root context. This child context typically contains web-specific beans like controllers, view resolvers, and handler mappings. The key benefit of this parent-child relationship is bean visibility: beans defined in a child context can access beans defined in its parent context, but not vice-versa. This promotes a clear separation of concerns, allowing you to define application-wide services once in the root context and reuse them across different web modules or servlets without duplication.
This hierarchical structure significantly improves modularity and maintainability. For example, if you have multiple DispatcherServlet instances serving different parts of your application (e.g., an admin interface and a public API), each can have its own child WebApplicationContext containing its specific controllers and configurations, all while sharing common service and repository beans from the single root ApplicationContext. This architectural pattern is highly recommended for larger Spring web applications to manage their dependency graph effectively.
Key Differences and Practical Use Cases
The fundamental difference between ApplicationContext and WebApplicationContext lies in their environment awareness and specialized functionalities. While both manage beans, the latter is specifically tailored for web environments, understanding concepts like ServletContext, request, and session scopes. Understanding these distinctions is crucial for designing efficient and robust Spring applications, whether they are standalone or web-based.
- Environment:
ApplicationContextis general-purpose, used in any Spring application.WebApplicationContextis web-specific, always tied to aServletContext. - Initialization:
ApplicationContextcan be initialized programmatically (e.g.,new ClassPathXmlApplicationContext()) or via Spring Boot.WebApplicationContextis typically initialized byContextLoaderListener(root context) orDispatcherServlet(servlet-specific context). - Scopes:
ApplicationContextsupports singleton and prototype scopes by default.WebApplicationContextextends these with web-specific scopes likerequest,session, andapplication. - Access to Web Resources: Only
WebApplicationContextprovides direct access toServletContextand its resources.
Practical Use Cases:
-
Standalone Applications: For a Spring Boot application Question & Answer :
What is the difference between Application Context and Web Application Context?I am aware that
WebApplicationContextis used for Spring MVC architecture oriented applications?I want to know what is the use of
ApplicationContextin MVC applications? And what kind of beans are defined inApplicationContext?Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it’s able to communicate with the container.
public interface WebApplicationContext extends ApplicationContext { ServletContext getServletContext(); }Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface
package org.springframework.web.context; public interface ServletContextAware extends Aware { void setServletContext(ServletContext servletContext); }There are many things possible to do with the ServletContext instance, for example accessing WEB-INF resources(xml configs and etc.) by calling the getResourceAsStream() method. Typically all application contexts defined in web.xml in a servlet Spring application are Web Application contexts, this goes both to the root webapp context and the servlet’s app context.
Also, depending on web application context capabilities may make your application a little harder to test, and you may need to use MockServletContext class for testing.
Difference between servlet and root context Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it’s not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet contexts:
.This allows you to run some services as the singletons for the entire application (Spring Security beans and basic database access services typically reside here) and another as separated services in the corresponding servlets to avoid name clashes between beans. For example one servlet context will be serving the web pages and another will be implementing a stateless web service.
This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/root-context.xml /WEB-INF/applicationContext-security.xml </param-value> </context-param>(the root application context is created by ContextLoaderListener which is declared in web.xml
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>) and servlet tag for the servlet application contexts
<servlet> <servlet-name>myservlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>app-servlet.xml</param-value> </init-param> </servlet>Please note that if init-param will be omitted, then spring will use myservlet-servlet.xml in this example.
See also: Difference between applicationContext.xml and spring-servlet.xml in Spring Framework