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

时间:2012-02-24 04:59:54

标签: hibernate java-ee dependency-injection spring-3 servlet-listeners

我使用的是Spring3 + Hibenate3,我是新手。所以没有太多的知识。 我想要从DAO方法调用的记录列表。 我试图获取列表,但它显示空指针异常。

任何人都可以告诉我如何在Spring3中配置ServletContextListener,这样我就可以从方法调用中获取记录列表...

谢谢。

1 个答案:

答案 0 :(得分: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>
相关问题