Singleton resources shared by several MVC controllers in Java
Is there a way to have a singleton resource used by multiple controllers?
We got 2 ser开发者_如何学JAVAvlets, each one with its own application contexts: one-servlet.xml & two-servlet.xml and lib-context.xml with singleton bean "util".
Now, if we import lib-context.xml into each of 2 servlet contexts above, spring will create a separate application context for each servlet and we'll end up with 2 singletone objects.
Is there a way to configure application that only one singleton object will be created?
Yes. In your web.xml
, load lib-context.xml
with the ContextLoaderListener
instead of loading it with the DispatcherServlet
.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/lib-context.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can remove the imports from your servlet-specific app context configuration files.
All the DispatcherServlet
s will see not only the shared lib-context.xml
above but also any contexts that they themselves load.
(You may need to adjust the param-value
example I gave. That path is just an example.)
精彩评论