This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Spring and the fly likes Need for the contextConfigLocation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Need for the contextConfigLocation" Watch "Need for the contextConfigLocation" New topic

Need for the contextConfigLocation

Amirtharaj Chinnaraj
Ranch Hand

Joined: Sep 28, 2006
Posts: 241

I have noticed many time ,their is context parameter set with the name contextConfigLocation, in web.xml as shown in the below code

Also the same parameter has been set in the Dispatch Servlet using the below code. As shown below

Ok , My questions is why dont we can have a single contextConfigLocation. In other sense why dont we configure them like the below one as shown

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

The init-param in the DispatcherServlet is used by the DispatcherServlet init method to create an ApplicationContext for your web layer beans.

The context-param is used by the ContextLoaderListener to create an ApplicationContext for you middle tier beans in a web application.

You end up with 2 Application Context instance a Parent one with middle tier beans and a Child one with the web layer beans. The Child has access to the Parent beans, but not the other way around. This way you can inject your middle tier beans like Services into you Web Layer beans like Services. But you would never want to inject your Web Layer Controller beans to be injected into your Services.

So they are for two different purposes.

There are some naming conventions you can use so you would need neither the context-param or the init-param

For the context-param ContextLoaderListener, if you put a file called applicationContext.xml in your WEB-INF directory, you don't have to put in the context-param

If you put a file called {{{servletName}}}-servlet.xml also in your WEB-INF directory, then you don't need the init-param in the DispatcherServlet. {{{servlet-name}}} is replaced with whatever name you give the DispatcherServlet in your web.xml. So in your example that would be spring-servlet.xml

In your example you put both config files for middle tier and web layer beans in your init-param you will get just one ApplicationContext with all your beans, and yes that will work, but it isn't a clean separation of layers. But it will work.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Need for the contextConfigLocation
jQuery in Action, 3rd edition