HttpSessionListener中使用依赖注入的方式完成Bean实例的注入
来源:互联网 发布:arm linux gcc 4.9.1 编辑:程序博客网 时间:2024/05/22 09:48
在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);
- }
- }
0 0
- HttpSessionListener中使用依赖注入的方式完成Bean实例的注入
- 2.bean的命名和实例化、依赖注入方式
- 依赖注入之Bean的实例化
- Bean的两种依赖注入方式
- Spring中bean的依赖注入解析
- 依赖注入的方式和注入的配置实例
- 依赖注入的方式
- 依赖注入的方式
- 依赖注入的方式
- 使用XPath解析xml实现简单的Spring IOC完成bean的依赖注入
- Spring依赖注入的过程,ref注入与内部bean方式注入
- Spring中bean的注入方式
- 依赖注入之Bean实例化前的准备
- 六、基于xml的bean实例化和依赖注入
- spring 配置bean的方法及依赖注入发方式
- Spring-2:bean的两种依赖注入方式
- spring 依赖注入的5中方式
- Spring的bean注入方式
- JAVA静态加载出错
- crf++-0.58java调用
- Objective-C类型推断
- java学习之IO字符流
- Debug VoltDB EE部分代码
- HttpSessionListener中使用依赖注入的方式完成Bean实例的注入
- Python脚本09 —— 一个计算题
- Android添加锁屏界面
- PF_Ring 编译安装 for Linux SUSE11 SP1
- 运用cocoapods管理三方开源框架
- __attribute__ noreturn
- sublime3的配置
- ElasticSearch线程池配置
- jQuery.extend 函数详解