What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?
Asked Answered
S

4

205

What is the difference between Application Context and Web Application Context?

I am aware that WebApplicationContext is used for Spring MVC architecture oriented applications?

I want to know what is the use of ApplicationContext in MVC applications? And what kind of beans are defined in ApplicationContext?

Slot answered 29/7, 2012 at 11:44 Comment(2)
I do not believe that is is a duplicate of #3652590 That question asks about the content of the web.xml file; this question is asking about some Spring classes.Eddie
@Eddie that's not true. The other question is not talking about web.xml but it's talking about the Spring XML bean configuration variants of ApplicationContext and WebApplicationContext. All bean definitions in applicationContext.xml will be available in the ApplicationContext while all bean definitions in *-servlet.xml will be available in a WebApplicationContext.Mulligan
E
241

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: Servlet and root context.

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

Etruscan answered 29/7, 2012 at 12:35 Comment(5)
Many thanks for the answer. I have heard that there are two types of contexts also used for a web-application. One serves as as root application context where non-web related definitions are provided example service, dao configurations etc, and the other is for web-specific configuration like Handler Mappings etc. The prior serves as a parent context and the latter serves as Child Context. I want to know how to declare this structure. I have heard of some ContextListener callbacks. But I am pretty unclear about it.Slot
Such structure is hardcoded in Spring servlet tools, there are always at least two application contexts in the spring web app, see the updated answer, i hope it helps.Etruscan
Excellent discription..i had some doubts on this scenario..as i am in initial stage i found your useful answer for getting some knowledge..Mcclendon
"required bean will be fetched from the parent context if it's not present in the current application context". Can you explain how? How a web application context can access beans in root application context? Link to any example?Windlass
Hi @BorisTreukhov, My understanding is: Even if we don't configure "contextConfigLocation" in MVC app, the root ApplicationContext still will be instantiated/created with out any configuration set. So we can say, an Spring Web app has at least two contexts instantiated by default: One WebApplicationContext & One Root ApplicationContext. Please correct me if I am wrong. Thanks!Lumpy
A
21

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

Addition answered 13/9, 2017 at 13:46 Comment(2)
Does this mean that my application can have 2 ServletContexts, and therefore 2 WebApplicationContexts? How exactly does spring distribute the beans between these contexts? @Service, @Controller, @Repository and others?Adverse
@SantaMonica In my understanding, you can only achieve that by using J2EE application server like tomcat, and tomcat will dispatch the request to right servlet(app). It has been a long time since I participate in projects like that, I am not certain now.Addition
Z
16

Going back to Servlet days, web.xml can have only one <context-param>, so only one context object gets created when server loads an application and the data in that context is shared among all resources (Ex: Servlets and JSPs). It is same as having Database driver name in the context, which will not change. In similar way, when we declare contextConfigLocation param in <contex-param> Spring creates one Application Context object.

 <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.myApp.ApplicationContext</param-value>
 </context-param>

You can have multiple Servlets in an application. For example you might want to handle /secure/* requests in one way and /non-seucre/* in other way. For each of these Servlets you can have a context object, which is a WebApplicationContext.

<servlet>
    <servlet-name>SecureSpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>com.myapp.secure.SecureContext</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>SecureSpringDispatcher</servlet-name>
    <url-pattern>/secure/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>NonSecureSpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>com.myapp.non-secure.NonSecureContext</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>NonSecureSpringDispatcher</servlet-name>
    <url-pattern>/non-secure/*</url-patten>
</servlet-mapping>
Zion answered 16/3, 2017 at 16:8 Comment(1)
Does this mean that my application can have 2 ServletContexts, and therefore 2 WebApplicationContexts? How exactly does spring distribute the beans between these contexts? @Service, @Controller, @Repository and others?Adverse
E
11

ApplicationContext (Root Application Context) : Every Spring MVC web application has an applicationContext.xml file which is configured as the root of context configuration. Spring loads this file and creates an applicationContext for the entire application. This file is loaded by the ContextLoaderListener which is configured as a context param in web.xml file. And there will be only one applicationContext per web application.

WebApplicationContext : WebApplicationContext is a web aware application context i.e. it has servlet context information. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.

Evangelina answered 6/2, 2019 at 4:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.