2

我正在使用Spring3 + Hibenate3,並且我對它很陌生。所以沒有太多的知識。 我想要從DAO方法中調用的記錄列表。 我想獲得列表,但它顯示空指針異常。如何在Spring3中訪問ServletContextListener中的DAO方法

任何人可以PLZ告訴我如何配置了ServletContextListener在Spring3,所以我可以從我的方法打電話是記錄列表...

謝謝。

回答

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> 
+0

提示錯誤:java.lang.IllegalStateException:沒有找到的WebApplicationContext:沒有ContextLoaderListener註冊? – 2012-02-25 09:22:51

+0

我已經更新了顯示如何註冊偵聽器的答案。 – ManuPK 2012-02-25 09:42:11

+0

我已經註冊了listner ....同樣的錯誤.. – 2012-02-25 11:31:03

相關問題