Tuesday, October 29, 2013

Are applicationContext.xml and spring-servlet.xml related anyhow in spring framework? Will the properties files declared in applicationContext.xml be available to DispatcherServlet? On a related note, why do I need a *-servlet.xml at all ? Why is applicationContext.xml alone insufficient?
share|improve this question

3 Answers

up vote101down voteaccepted
Spring lets you define multiple contexts in a parent-child hierarchy.
The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.
The spring-servlet.xml (or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xmlfor servlet spring1spring2-servlet.xml for servlet spring2).
Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa.
All Spring MVC controllers must go in the spring-servlet.xml context.
In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.
share|improve this answer
4 
why would you have multiple spring servlets ? –  NimChimpsky Aug 14 '12 at 9:59
2 
mighty potent answer (because of succinctness) –  amphibient Mar 15 at 16:44
3 
@NimChimpsky it is sometimes useful to separate parts of your application that could otherwise conflict in the same context. As an example you may have ReST services and standard views, you may then have different view resolvers or security concerns for the services as to the views. –  Brett Ryan Apr 3 at 17:19
2 
People should see this answer before reading documentation and developing apps! In normal cases there is no need to have ContextLoaderListener and contextConfigLocation at all, just DispatcherServlet! –  ruruskyiJun 28 at 13:11 
2 
In many tutorials contextConfigLocation contains dispatcher-servlet.xml as well as DispatcherServlet. This causing beans to be initialized twice! –  ruruskyi Jun 28 at 13:24 
show 2 more comments

No comments: