在Spring3中如何在ServletContextListener中访问DAO方法

3

我正在使用Spring3和Hibernate3,但是我对它们不太了解。我想要一个从DAO方法中调用的记录列表。我正在尝试获取这个列表,但它显示出空指针异常。

请问有人可以告诉我如何在Spring3中配置ServletContextListener,以便我可以从调用的方法中获得记录列表吗?

谢谢!

1个回答

0
以下代码将会帮助您,
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>

它报错了:java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? - Naresh J
我已经更新了答案,展示了如何注册监听器。 - ManuPK
1
重要提示:在web.xml中,ContextLoaderListener必须在MyServletListener之前加载。否则你将会遇到错误信息“java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered”。 - Nico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接