【问题标题】:How to access DAO methods in ServletContextListener in Spring3Spring3中如何访问ServletContextListener中的DAO方法
【发布时间】:2012-03-14 14:25:51
【问题描述】:

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

谁能告诉我如何在 Spring3 中配置 ServletContextListener,以便我可以从我正在调用的方法中获取记录列表...

谢谢。

【问题讨论】:

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


    【解决方案1】:

    下面的代码会帮助你,

    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?
    • 我已经更新了显示如何注册监听器的答案。
    • 重要:在 web.xml 中 ContextLoaderListener 必须在 MyServletListener 之前加载。否则会报错“java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered”
    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    相关资源
    最近更新 更多