What is the correct way to use the two contexts: dispatcher-servlet.xml
and applicationContext.xml
? What goes where?
I want to write a fairly typical app deployed in a servlet container. It has some controllers with JSP views. It also has some nontrivial logic on the back-end. Do I really need both contexts? How are they related to each other? How can I decide what to put in which?
Also, I want to use Spring-security for my application. I may want to use its features (like declarative security with annotations) in web controllers as well as in deeper layers. How should I configure security to work in this case? Should it be in one of those files (which?), or both?
To add to Kevin's answer, I find that in practice nearly all of your non-trivial Spring MVC applications will require an application context (as opposed to only the spring MVC dispatcher servlet context). It is in the application context that you should configure all non-web related concerns such as:
To make this a bit more concrete, here's an example of the Spring configuration I've used when setting up a modern (Spring version 4.1.2) Spring MVC application. Personally, I prefer to still use a
WEB-INF/web.xml
file but that's really the only xml configuration in sight.WEB-INF/web.xml
WebConfig.java
AppConfig.java
Security.java
PersistenceConfig.java
ScheduleConfig.java
As you can see, the web configuration is only a small part of the overall spring web application configuration. Most web applications I've worked with have many concerns that lie outside of the dispatcher servlet configuration that require a full-blown application context bootstrapped via the
org.springframework.web.context.ContextLoaderListener
in theweb.xml
.The
dispatcher-servlet.xml
file contains all of your configuration forSpring MVC
. So in it you will find beans such asViewHandlerResolvers
,ConverterFactories
,Interceptors
and so forth. All of these beans are part ofSpring MVC
which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.The
application-context.xml
can optionally be included when usingSpring MVC
or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.These configuration files are configured in the web.xml file as shown:
Dispatcher Config
Application Config
To configure controllers, annotate them with
@Controller
then include the following in thedispatcher-context.xml
file: