Since you have a web application, I would go with a WebApplicationContext
contained in spring-web
, which is loaded at deploy-time of your web application and properly closed on undeploy. All you have to do is declaring the ContextLoaderListener
in your web.xml
:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
Then you can access your ApplicationContext
from any servlet:
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
MyBean myBean = (MyBean) ctx.getBean("myBean");
myBean.doSomething();
The advantage is, that your context is shared between all servlets.
References: