在我的应用程序中,我希望将我的一些数据存储在ServletContext中,因为它将在整个应用程序中使用。数据保存在数据库中。所有的配置都是通过集成struts2,spring,hibernate来完成的。问题是,我发现从数据库获取数据很困难。Spring无法将dao类注入到实现ServleltContextListener的类中。有人能告诉我怎么做吗?或者还有其他选择吗?
发布于 2012-07-02 19:58:53
尝尝这个
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)
{
}
}希望这能起作用。让我知道进展如何。
发布于 2012-07-03 00:18:26
最好的方法是实现servlet接口,然后使用@PostConstruct或afterPropertiesSet方法将项添加到ServletContextAware上下文。
https://stackoverflow.com/questions/11293041
复制相似问题