Sunday, 27 September 2015

Context loading in Spring MVC


Spring need no introduction. It is a well know Java framework that use DI (dependency Injection) or Ioc (Inversion of control). I have previously written couple of posts on Spring which you can read in the Related Links section at the bottom of this post. In this post I am specifically going to write about Spring context and how is it loaded.

Context loading in Spring MVC

We generally load spring context in deployment descriptor file called web.xml that is generally located under WEB-INF directory of the projects war file. There are two ways the context can be loaded

  1. You can load the context using ApplicationContext in which case the loaded context will be accessible to entire Application (including various configured endpoints like Dispacher Servlet, Webservice Servlet, REST servlet etc). OR
  2. you can load the context that is specific to an entry point (WebApplicationContext). For example loading context just for Dispacher Servlet. OR
  3.  Use combination of both. Use Application context to load your backend service, access or repository beans that will be used by entire application and your controller, view resolver beans in WEbApplicationContext.

Lets see each in detail

Application  Context

You can do this like follows - 



  • Default name of this file is applicationContext.xml. If you do not provide application context configuration file in web.xml using contextConfigLocation as mentioned in config above then file named applicationContext.xml is searched in under WEB-INF folder.
  • There can be only one application context per web application.


You can do that as follows - 


  • Default name of this file is xxx-servlet.xml where xxx is the DispatcherServlet name in web.xml
  • A web application can have multiple Dispacher servlets and thereby have multiple such webapplication contexts.

  1. Application Context is parent context of each WebApplication Contexts.
  2. If a bean is not found in a particular wevbapplication context it is then searched in the parent application context.
  3. Application context is basically to initialize beans that are singleton in nature and can be used throughout the application like your data access bean or your service beans.

Related Links

t> UA-39527780-1 back to top