Hibernate 如何在Spring3中访问ServletContextListener中的DAO方法
我正在使用Spring3+Hibenate3,而且我是新手。所以我没有太多的知识。 我想要从DAO方法调用的记录列表。 我试图获取列表,但它显示空指针异常 有谁能告诉我如何在Spring3中配置ServletContextListener,这样我就可以从我调用的方法中获取记录列表Hibernate 如何在Spring3中访问ServletContextListener中的DAO方法,hibernate,jakarta-ee,dependency-injection,spring-3,servlet-listeners,Hibernate,Jakarta Ee,Dependency Injection,Spring 3,Servlet Listeners,我正在使用Spring3+Hibenate3,而且我是新手。所以我没有太多的知识。 我想要从DAO方法调用的记录列表。 我试图获取列表,但它显示空指针异常 有谁能告诉我如何在Spring3中配置ServletContextListener,这样我就可以从我调用的方法中获取记录列表 谢谢。下面的代码将帮助您 public class MyListener implements ServletContextListener { private ApplicationContext appl
谢谢。下面的代码将帮助您
public class MyListener implements ServletContextListener {
private ApplicationContext applicationContext;
private MyDAO myDAO;
public void contextInitialized(ServletContextEvent event) {
applicationContext = getContext(event);
myDAO = applicationContext.getBean("myDAO");
performAction();
}
public void contextDestroyed(ServletContextEvent event) {
}
/**
* Gets the ApplicationContext from the ServletContextEvent.
*
* @param event
* @return ApplicationContext.
*/
private ApplicationContext getContext(ServletContextEvent event) {
return WebApplicationContextUtils
.getRequiredWebApplicationContext(event.getServletContext());
}
void performAction(){
myDAO.getTheNeededData();
}
}
要添加侦听器,请在web.xml
中添加以下行
<listener>
<listener-class>com.foo.MyListener</listener-class>
</listener>
com.foo.MyListener
它给出错误:java.lang.IllegalStateException:未找到WebApplicationContext:未注册ContextLoaderListener?我已更新了说明如何注册侦听器的答案。重要提示:在web.xml中,必须在MyServletListener之前加载ContextLoaderListener。否则,您将出现错误“java.lang.IllegalStateException:未找到WebApplicationContext:未注册ContextLoaderListener”