Difference between applicationContext.xml and spring-servlet.xml in Spring

04-02-2015
QUESTION:

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?

Note: For example, mvc-dispatcher-servlet.xml is an spring-servlet.xml file.

ANSWER 1:

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.xml for servlet spring1, spring2-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.


ANSWER 2

One more point I want to add. In spring-servlet.xml we include component scan for Controller package. In following example we include filter annotation for controller package.

<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>


In applicationcontext.xml we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

Debate:

why ? Why not just scan the whole thing one time ? – NimChimpsky Aug 14 '12 at 9:57
  
@NimChimpsky You have to scan @Controller beans in servlet context (required by Spring MVC). – Tuukka Mustonen Nov 21 '12 at 12:22

Why not can the whole thing twice? Why include/exclude? – Mike Rylander Jul 5 '13 at 16:26

One should also add use-default-filters="false" attribute in spring-servlet.xml – Rakesh Waghela Feb 25 '14 at 9:51

Rakesh Waghela has point. Without that attribute Controller beans will be created twice. Firstly in appContext and secondly in servletContext

© 2019 All rights reserved. Codesenior.COM