Issue
I have a big java project that contains many servlets. and each servlet needs to get objects from the same bean file using the following command:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
context.getBean("<BEAN_NAME">);
some of them even needs to get same objects.
the question is if it's possible to inject the object that I want directly to the servlets without reading the bean file manually.
each servlet is configured in web.xml.
any information regarding the issue would be greatly appreciated!
thanks
Solution
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:
- How to get the default WebApplicationContext?
- Integration of ContextLoaderListener
- WebApplicationContextUtils Javadoc
Answered By - nif
Answer Checked By - Candace Johnson (JavaFixing Volunteer)