Two Contexts in Spring MVC applications – Application Context, WebApplicationContext

By W.ZH Sept 2016

If you directly start learning Spring from the Spring MVC. then you may be ignored a context issue. MVC works in a context called webapplicationcontext  or servlet context. besides this one spring itself already has a root context or application context. So there are some very important points you must be clear on these two:

  • Application Context default use this files as config file – applicationContext.xml . One web application only has one Application Context. Spring loads applicationContext.xml file and creates the ApplicationContext for the whole application. if you have more than one config files for the context, you can config them in the web.xml as the <context-param>:
<web-app ..... >
....
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml, classpath:spring-security.xml</param-value>
    </context-param>
...
</web-app>

  • Spring security is in the root context – Application Context, not in the WebApplicationContext
  • Each DispatcherServlet associated with single WebApplicationContext. There can be multiple WebApplicationContext in a single web application.each DispatcherServlet could have one xml config used. in Web.xml it looks like this:
     <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc-dispatcher.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
  • WebApplicationContext is a child of “ApplicationContext”, You can access bean in the root context from the WebApplicationContext, but you can not access the bean in the WebApplicationContext from root context.
  • WebApplicationContext contains the  controllers, RestControllers and view resolvers. Root context contains other services, components, DAO access  initialized by the ContextLoaderListener.
  • If you define a property-placeholder in one context, it can not be accessed from another context. This means if you have one properties files need be accessed by @Value in two context, you need to insert this piece config in both context’s xml file”
<context:property-placeholder location="classpath:myConfigProp.properties"
        ignore-resource-not-found="true" />

 

Refer to:

https://spring.io/understanding/application-context

http://hmkcode.com/spring-mvc-share-root-webapplicationcontext-beans-with-child-webapplicationcontext/

 

Advertisements