With Spring/MVC I often struggle determining which context I should define beans, either the root-context.xml or the servlet-context.xml. What’s caused the confusion is I haven’t seen any documentation on the subject as to what to put where, in the spring sample code I often see the same thing defined in different contexts between samples.
As a rule of thumb I’ve presently defined anything that’s a service or a component in the root context, and reserved the servlet context for web controllers, interceptors and anything that’s only really related to web.
But what about security? I’ve presently defined it as an include of the root context, but is this correct?
Am I right in my understanding that the web context is actually a child context of the application root context?
Why do we need the web context to be separate?
I’ve read the spring documentation from 3.0 a couple of years ago but can’t remember anything specific to this, I’ve also read Spring in Action, Third Edition. I would love any material surrounding this topic.
There can and is usually a difference.
Basically you
applicationContext.xmlis your root context and is where your service and data layer beans live.*-servlet.xmlorwebmvc-config.xmlare special in that they:DispatcherServletassociatedWebApplicationContextbean factoryWebApplicationContext)But the biggest reason people do this is for unit testing, decoupling frontend from backend, and for separate view resolvers and/or multiple dispatcher servlets.
It’s good for unit testing because you are loading less beans for testing your service layer. As I stated in my comments below I usually load my real
applicationContext.xmllike:Also because the servlet context requires a dispatcher servlet you need to register it as servlet like:
So while you maybe able to load our MVC controller beans with the root context they aren’t really registered unless a dispatcher servlet is controlling that context. Although in theory I think the
DispatcherServletcan load configs in the classpath notice that the contextConfigLocation value is not in the classpath.Also some people need multiple dispatcher servlets because of some of the limitations in that you can typically only have one resolver chain (view, locale, theme, etc…).