zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    api服务器思路
    利用express写api接口
    sql基础语句
    安装npm后,nrm ls 报错internal/validators.js:124 throw new ERR_INVALID_ARG_TYPE(name, ‘string‘, value)
    JavaScript垃圾回收机制和闭包
    用git clone 远程的所有分支
    面试题重点
    Linux 常用命令
    防抖函数和节流函数
    GIT PUSH 出现EVERYTHING UP-TO-DATE 解决方法
  • 原文地址:https://www.cnblogs.com/king1302217/p/4195659.html
Copyright © 2011-2022 走看看