Reputation: 1777
In my application I want to store some of my data in ServletContext as its going to be used through out the application. Data are saved in a database. All the configurations are made through integrating struts2, spring, hibernate. Problem is that, I am finding difficulties to fetch the data from the database. Spring is unable to inject the dao impl class to the class that is implementing the ServleltContextListener. Can anyone please tell me how to do this? Or is there any alternative?
Upvotes: 3
Views: 2522
Reputation: 1576
The best approach would be to implement Spring's ServletContextAware interface and then use an @PostConstruct or afterPropertiesSet method to add items to the servlet context.
Upvotes: 1
Reputation: 3204
Try this
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class MyListener implements ServletContextListener
{
/**
* @see javax.servlet.ServletContextListener#contextInitialized
* (javax.servlet.ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent sce)
{
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
Object yourDaoImplClass = applicationContext.getBean("your_bean_name_or_bean_id");
//You can type cast yourDaoImplClass to your object
}
/**
* @see javax.servlet.ServletContextListener#contextDestroyed
* (javax.servlet.ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent sce)
{
}
}
Hope this works. Let me know how it goes.
Upvotes: 4