• spring listener引用spring中bean


          在SSH项目开发中,会使用到监听器Listener,并且有时需要在监听器中完成数据库的操作等动作,此时需要在Listener中使用到Spring容器中的Bean。Spring容器本身就是在web.xml中使用listener的方式启动的。想在例如HttpSessionListener中使用依赖注入的方式完成Bean实例的注入,不能完成。

          一种解决方案:在HttpSessionListener中通过new的方式得到Spring容器的实例。如下代码:

    //通过new的方式得到Spring容器的实例  
    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); 

          结果是:可以取得Spring的容器,但是是重新生成了一个新的Spring的容器。SSH项目启动的时候已经自动生成了一个Spring的容器,这样就存在了两个Spring的容器。不可取。

          最好的解决方案:通过Spring提供的WebApplicationContextUtils 得到Spring容器的实例。代码如下:

    public class MySessionListener implements HttpSessionListener {
        private Logger logger=Logger.getLogger(MySessionListener.class);
        
        @Override
        public void sessionCreated(HttpSessionEvent event) {
            logger.debug("新的session的产生!!");
            HttpSession session=event.getSession();
            session.setAttribute(InitUtil.ISNEWSESSION, "true");
            //通过抽象的私有方法得到Spring容器中Bean的实例。
            UsersDao userDao=(UsersDao)this.getObjectFromApplication(session.getServletContext(), "usersDaoHibernate");
            System.out.println("取得的Dao的实例="+userDao);
            
        }
        /**
         * 通过WebApplicationContextUtils 得到Spring容器的实例。根据bean的名称返回bean的实例。
         * @param servletContext  :ServletContext上下文。
         * @param beanName  :要取得的Spring容器中Bean的名称。
         * @return 返回Bean的实例。
         */
        private Object getObjectFromApplication(ServletContext servletContext,String beanName){
            //通过WebApplicationContextUtils 得到Spring容器的实例。
            ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);
            //返回Bean的实例。
            return application.getBean(beanName);
        }
    }

    本文转载自http://wxinpeng.iteye.com/blog/1317659

  • 相关阅读:
    《分布式系统关注点——数据一致性(上篇)》阅读笔记
    2.23寒假学习记录
    2.22寒假学习记录
    2.21寒假学习记录
    2.20寒假学习记录
    2.19寒假学习记录
    2.18寒假学习记录
    2.17寒假学习记录
    2.17周一毕设改进计划
    2.16寒假学习记录
  • 原文地址:https://www.cnblogs.com/king1302217/p/4195659.html
Copyright © 2020-2023  润新知