Is there a way to have a singleton resource used by multiple controllers?
We got 2 servlets, 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, loadlib-context.xmlwith theContextLoaderListenerinstead of loading it with theDispatcherServlet.You can remove the imports from your servlet-specific app context configuration files.
All the
DispatcherServlets will see not only the sharedlib-context.xmlabove but also any contexts that they themselves load.(You may need to adjust the
param-valueexample I gave. That path is just an example.)