psms
psms

Reputation: 883

Spring : Need for the contextConfigLocation?

In web.xml we have context parameter set named contextConfigLocation and defined as shown in the below code:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
</context-param>

Also the same parameter is set in the Dispatch Servlet as shown below

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

What is the difference between these two contextConfigLocations ?

Upvotes: 2

Views: 2384

Answers (3)

Karan Kaw
Karan Kaw

Reputation: 539

  • contextConfigLocation in context-param gets Loaded, when We start Our Web Container or server
  • It usually has DAOImpl, Service, Singleton, Datasource Helper Objects etc , those objects We want to be ready before hand so that they can be used

  • contextConfigLocation in init-param is specific to that DispatcherServlet Only and gets Loaded as soon as Servlet Starts up which may be Lazily loaded i.e on first call to Servlet, if load-on-startup is not a positive value for that servlet.
  • This means, Beans defined here could be possibly created later. It usually contains Controller Beans etc

  • Beans defined in context-param ContextXml are visible to Beans defined in init-param ContextXml
  • But the Beans defined in init-param are not visible to context-param context Beans
  • So @Controller Bean is usually defined in ChildApplicationContext while @Service is a part of RootApplicationContext
  • This means @Controller cannot be injected in @Service While as we easily can easily inject @Service Bean in @Controller

So basically we control Visibility (not scope ) of Beans by having different context-config files

Upvotes: 2

Sai prateek
Sai prateek

Reputation: 11926

There are two types of contexts:

Root context (Super)

Own (child) servlet context (Sub)

As generic application contexts, web application contexts are hierarchical. There is a single root context per application, while each servlet in the application (including a dispatcher servlet in the MVC framework) has its own child context.

Upvotes: 1

Palcente
Palcente

Reputation: 635

The fist setting applies globally, whilst second setting is private and exclusive to the "spring" servlet.

Upvotes: 2

Related Questions