正好以前项目中碰到这个问题,现在网上偶然又看到这个问题的博文,那就转一下吧。

原文:http://blog.lifw.org/post/46428852 感谢作者

另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对象,当然除了下面我们详细说的方法外,还有的比如说为了在Servlet中使用Spring容器的对象,那么可以参考如下两篇文章:

Servlet自动注入Spring容器中的Bean解决方法

在servlet中注入spring的bean,servlet容器和spring容器

额外文章就参考这么多

以下是原文:

1.在java web项目中我们通常会有这样的需求:当项目启动时执行一些初始化操作,例如从数据库加载全局配置文件等,通常情况下我们会用javaee规范中的Listener去实现,例如

1 public class ConfigListener implements ServletContextListener {
2 @Override
3 public void contextInitialized(ServletContextEvent sce) {
4 //执行初始化操作
5 }
6 @Override
7 public void contextDestroyed(ServletContextEvent sce) {
8 }
9 }

2.这样当servlet容器初始化完成后便会调用contextInitialized方法。但是通常我们在执行初始化的过程中会调用service和dao层提供的方法,而现在web项目通常会采用spring框架来管理和装配bean,我们想当然会像下面这么写,假设执行初始化的过程中需要调用ConfigService的initConfig方法,而ConfigService由spring容器管理(标有@Service注解)

public class ConfigListener implements ServletContextListener {

    @Autowired
private ConfigService configService; @Override
public void contextInitialized(ServletContextEvent sce) {
configService.initConfig();
} @Override
public void contextDestroyed(ServletContextEvent sce) {
}
}

3.然而以上代码会在项目启动时抛出空指针异常!ConfigService实例并没有成功注入。这是为什么呢?要理解这个问题,首先要区分Listener的生命周期和spring管理的bean的生命周期。

(1)Listener的生命周期是由servlet容器(例如tomcat)管理的,项目启动时上例中的ConfigListener是由servlet容器实例化并调用其contextInitialized方法,而servlet容器并不认得@Autowired注解,因此导致ConfigService实例注入失败。

(2)而spring容器中的bean的生命周期是由spring容器管理的。

4.那么该如何在spring容器外面获取到spring容器bean实例的引用呢?这就需要用到spring为我们提供的WebApplicationContextUtils工具类,该工具类的作用是获取到spring容器的引用,进而获取到我们需要的bean实例。代码如下

public class ConfigListener implements ServletContextListener {

    @Override
public void contextInitialized(ServletContextEvent sce) {
ConfigService configService = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(ConfigService.class);
configService.initConfig();
} @Override
public void contextDestroyed(ServletContextEvent sce) {
} }

注意:以上代码有一个前提,那就是servlet容器在实例化ConfigListener并调用其方法之前,要确保spring容器已经初始化完毕!而spring容器的初始化也是由Listener(ContextLoaderListener)完成,因此只需在web.xml中先配置初始化spring容器的Listener,然后在配置自己的Listener,配置如下

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <listener>
<listener-class>example.ConfigListener</listener-class>
</listener>

如何在自定义Listener(监听器)中使用Spring容器管理的bean的更多相关文章

  1. 如何在servlet的监听器中使用spring容器的bean

    另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对 ...

  2. 在Listener(监听器)定时启动的TimerTask(定时任务)中使用Spring@Service注解的bean

    1.有时候在项目中需要定时启动某个任务,对于这个需求,基于JavaEE规范,我们可以使用Listener与TimerTask来实现,代码如下: public class TestTaskListene ...

  3. Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)

    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...

  4. 在listener或者工具中使用spring容器中的bean实例

    在项目中经常遇见需要在Listener中或者工具中使用Spring容器中的bean实例,由于bean不能在stataic的类中使用. 介绍一种方式: public class SpringTool { ...

  5. Spring--------web应用中保存spring容器

    ---恢复内容开始--- 问题:在一个web应用中我使用了spring框架,但有一部分模块或组件并没有托管给Spring,比如有的可能是一个webservice服务类,如果我想在这些非托管的类里使用托 ...

  6. 49、[源码]-Spring容器创建-创建Bean准备

    49.[源码]-Spring容器创建-创建Bean准备

  7. 配置springmvc在其他类中(spring容器外)获取注入bean

    学习https://github.com/thinkgem/jeesite 今天在写JedisUtils的时候要注入JedisPool,而这个属性被设置为static,@Resource和@Autow ...

  8. 如何在非Spring管理的类中使用Spring加载的bean

    <dependencies> <dependency> <groupId>org.springframework.boot</groupId> < ...

  9. 在Spring容器外调用bean

    这个东西源于这种需求:一个应用丢到服务其后,不管用户有没有访问项目,这个后台线程都必须给我跑,而且这个线程还调用了Spring注入的bean,这样自然就会想到去监听Servlet的状态,当Servle ...

随机推荐

  1. 解决方案--java执行cmd命令ProcessBuilder--出错Exception in thread "main" java.io.IOException: Cannot run program "dir d:\": CreateProcess error=2(xjl456852原创)

    当我尝试在java中通过ProcessBuilder运行window的cmd命令时出现错误: public static void main(String [] args) throws IOExce ...

  2. python ctypes小例子

    import time import ctypes import ctypes.wintypes SEE_MASK_NOCLOSEPROCESS = 0x00000040 SEE_MASK_INVOK ...

  3. (转)直接保存对象的数据库——db4o

    在实际开发中,数据的存储是必不可少的,常用的有数据库存储和文件存储.数据库目前有关系型数据库和文档型数据库(No-SQL).关系型数据库以字段.类型.约束.表关系来存储和管理数据,比较常见的比如Ora ...

  4. 为MyEclipse加入自己定义凝视

    非常多时候我们默认的MyEclipse的类凝视是这种,例如以下图 能够通过改动MyEclipse的凝视规则来改变,不但能够改动类的.还能够改动字段.方法等凝视规则,操作方法例如以下 1.针对方法的凝视 ...

  5. Timus 1796. Amusement Park 聪明题

    On a sunny Sunday, a group of children headed by their teacher came to an amusement park. Aunt Frosy ...

  6. hdu4756 Install Air Conditioning(MST + 树形DP)

    题目请戳这里 题目大意:给n个点,现在要使这n个点连通,并且要求代价最小.现在有2个点之间不能直接连通(除了第一个点),求最小代价. 题目分析:跟这题一样样的,唉,又是原题..先求mst,然后枚举边, ...

  7. [CSAPP笔记][第六章存储器层次结构]

    第六章 存储器层次结构 在简单模型中,存储器系统是一个线性的字节数组,CPU能够在一个常数访问每个存储器位置. 虽然是一个行之有效的模型,但没有反应现代系统实际工作方式. 实际上,存储器系统(memo ...

  8. EF中的TPH、TPT、TPC

    1. Table Per Hierarchy(TPH):只建立一个表,把基类和子类中的所有属性都映射为表中的列2. Table Per Type(TPT):为基类和每个子类建立一个表,每个与子类对应的 ...

  9. 网站全局js代码

    这几天开始看公司的一套系统,整理的网站全局js代码 /*文件名:base.js功能说明:全站通用的全局变量及公用方法创建日期:2010-09-26*///引入jquery库文件document.wri ...

  10. Asp.net实现在线人数统计功能代码实例

    application最经典的一个方法:统计在线人数,这需要借助于我们的全局应用程序类来对登录的用户信息进行统计: 以下是代码片段:    void application_start(object ...