Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need for the contextConfigLocation

 
Amirtharaj Chinnaraj
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic