Issue
So I have seen this question:
Spring dependency injection to other instance
and was wondering if my method will work out.
1) Declare beans in my Spring application context
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="validationQuery" value="${jdbc.validationQuery}" />
<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
</bean>
<bean id="apiData" class="com.mydomain.api.data.ApiData">
<property name="dataSource" ref="dataSource" />
<property name="apiLogger" ref="apiLogger" />
</bean>
<bean id="apiLogging" class="com.mydomain.api.data.ApiLogger">
<property name="dataSource" ref="dataSource" />
</bean>
2) Override my servlet's init method as shown:
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
this.apiData = (ApiData)ac.getBean("apiData");
this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
}
Will this work or is Spring not yet ready to deliver beans to my servlet at this point in the web applications deployment? Do I have to do something more traditional like putting the beans in web.xml
?
Solution
What you are trying to do will make every Servlet
have its own ApplicationContext
instance. Maybe this is what you want, but I doubt it. An ApplicationContext
should be unique to an application.
The appropriate way to do this is to setup your ApplicationContext
in a ServletContextListener
.
public class SpringApplicationContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
sce.getServletContext().setAttribute("applicationContext", ac);
}
... // contextDestroyed
}
Now all your servlets have access to the same ApplicationContext
through the ServletContext
attributes.
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute("applicationContext");
this.apiData = (ApiData)ac.getBean("apiData");
this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
}
Answered By - Sotirios Delimanolis