I have configured the root application context using ContextLoaderListener
and the context init-parameter contextConfigLocation
.
The root context is then accessed by JSF (*.jsf) variable-resolver. It works fine.
Now the problem is, the requests (*.do) going thru DispatcherServlet
will get another application context, and singleton beans are then instantiated twice.
I don't need another application context for DispatcherServlet
, how can I specify it to re-use the existing root application context, which is loaded by ContextLoaderListener
?
NOTE
After read the reference pages in answers, I know there is a context separation between the root context and the dispatcher context, but none of the references tell me where to go. So here is my solution, maybe helpful for other people facing the similar question:
In the context config XML for the dispatcher servlet:
dispatcher-servlet.xml
, I have duplicated defined<context:component-scan/>
which is already defined in the root context. So remove it. Thedispatcher-servlet.xml
only have to define those beans used for Spring MVC only.All the controllers have already been scanned and instantiated in the root context, however, Spring MVC by default doesn't register the controllers in the root context for request mappings. You can either:
2.1. In the root context, exclude
@Controller
from<component-scan>
, and scan@Controller
only in the dispatcher-servlet.xml.2.2. Or, set the property
DefaultAnnotationHandlerMapping.detectHandlersInAncestorContexts
to true:(dispatcher-servlet.xml:) <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="detectHandlersInAncestorContexts" value="true" /> </bean>