这个东西源于这种需求:一个应用丢到服务其后,不管用户有没有访问项目,这个后台线程都必须给我跑,而且这个线程还调用了Spring注入的bean,这样自然就会想到去监听Servlet的状态,当Servlet初始化完毕后会调用ServletContextListener中的contextInitialized方法,所以可以创建一个监听器继承ServletContextListener类来监听Servlet的状态,在contextInitialized方法中来启动后台的线程,但是如何使用Spring注入的bean呢?所以必须确保在启动线程前Spring容器必须初始化完毕,Spring的初始化也是有Listener完成的,所以这里特别注意的是自定的监听器必须放在Spring的监听器之后(很重要),否则无法获取bean属性,会报空指针异常!

1.创建监听器

package com.hhu.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.hhu.threads.DiagnosisThread; /**
* 这个监听器在WEB容器初始化后就立刻启用了
* @author Weiguo Liu
* @data 2017年11月30日
*/ public class ContextListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("加载应用程序...");
// StationService stationService = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(StationService.class);
// System.out.println("stationService=" + stationService); /*
* 创建诊断线程并启动
*/
DiagnosisThread dt = new DiagnosisThread();
dt.start();
System.out.println("Listener继续执行");
} @Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub } }
 

2.web.xml配置启动顺序

  <!-- 这里不能少,web启动后会按这个位置寻找Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-*.xml
</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <listener>
<listener-class>
com.hhu.listener.ContextListener
</listener-class>
</listener> <servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
 

3.写一个获取Spring Bean的工具类

由于ServletContextListener并不被Spring管理,所以我们不能使用@Autowired注解来获取相应的bean属性,而是利用ApplicationContext来获取Bean,代码如下

package com.hhu.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; /**
* 使用getBean可以获取对应的bean,自己的的手动进行类型强转
* 创建获取SpringBean的工具类
* @author Weiguo Liu
*
*/
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
} public static Object getBeanByName(String beanName) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(beanName);
} public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
}

这样以后就可以在后台线程中愉快的获取Spring bean了,这个工具类很强大,只要Spring初始化后,不管所在类是否被Spring管理,都可以使用如下的方式获取

bean的类型 bean的名字 = (bean的类型)SpringBeanUtil.getBeanByName("bean的名字");

做的越多,也就发现自己不懂的越多,还是要深入理解其原理啊

在Spring容器外调用bean的更多相关文章

  1. Spring—容器外的Bean使用依赖注入

    认识AutowireCapableBeanFactory AutowireCapableBeanFactory是在BeanFactory的基础上实现对已存在实例的管理.可以使用这个接口集成其他框架,捆 ...

  2. 如何在自定义Listener(监听器)中使用Spring容器管理的bean

    正好以前项目中碰到这个问题,现在网上偶然又看到这个问题的博文,那就转一下吧. 原文:http://blog.lifw.org/post/46428852 感谢作者 另外补充下:在web Server容 ...

  3. 7 -- Spring的基本用法 -- 4... 使用 Spring 容器:Spring 容器BeanFactory、ApplicationContext;ApplicationContext 的国际化支持;ApplicationContext 的事件机制;让Bean获取Spring容器;Spring容器中的Bean

    7.4 使用 Spring 容器 Spring 有两个核心接口:BeanFactory 和 ApplicationContext,其中ApplicationContext 是 BeanFactory ...

  4. 7 -- Spring的基本用法 -- 5... Spring容器中的Bean;容器中Bean的作用域;配置依赖;

    7.5 Spring容器中的Bean 7.5.1 Bean的基本定义和Bean别名 <beans.../>元素是Spring配置文件的根元素,该元素可以指定如下属性: default-la ...

  5. SpringBoot 之 普通类获取Spring容器中的bean

    [十]SpringBoot 之 普通类获取Spring容器中的bean   我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器 ...

  6. 【String注解驱动开发】面试官让我说说:如何使用FactoryBean向Spring容器中注册bean?

    写在前面 在前面的文章中,我们知道可以通过多种方式向Spring容器中注册bean.可以使用@Configuration结合@Bean向Spring容器中注册bean:可以按照条件向Spring容器中 ...

  7. 从Spring容器中获取Bean。ApplicationContextAware

    引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...

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

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

  9. 获取Spring容器中的Bean协助调试

    在使用Spring进行开发时,有时调bug真的是很伤脑筋的一件事,我们可以通过自定义一个监听器来获取Spring容器中的Bean实例来协助我们调试. 第一步:编写自定义监听器 /** * 监听serv ...

随机推荐

  1. zencart产品属性dropmenu select只有一个选择项时自动变成radio单选的解决办法

    includes\modules\classic\attributes.php 在大约786行代码 case ($products_options->RecordCount() == 1): 的 ...

  2. maven私仓搭建——nexus3

    maven私仓搭建——nexus3本文主要介绍maven私仓在windows下的搭建.本文主要参考:http://www.cnblogs.com/bingyeh/p/5913486.html好,下面上 ...

  3. Adboost几个要点分析

    1.本质就是前向步进算法和加法模型,每一步计算分类器权重alpha和基分类器. 2.总体降低指数误差函数,转化为每一步降低分类误差率. 因为右边可以看作常数,所以相当于对这个进行优化 但是这一步可能做 ...

  4. 【leetcode】1252. Cells with Odd Values in a Matrix

    题目如下: Given n and m which are the dimensions of a matrix initialized by zeros and given an array ind ...

  5. 《剑指offer》算法题第四天

    今日题目: 二进制中1的个数 数值的整数次方 调整数组顺序使奇数位于偶数前面 链表中倒数第K个节点 链表中环的入口节点 今天的题目都比较简单,但是前三道题都有不同的解法,4,5两题就不在这边讨论了,其 ...

  6. List集合遍历的三种方法

    测试数据: List<String> list = new ArrayList<String>(); list.add("java"); list.add( ...

  7. 【杂题】[AGC034F] RNG and XOR【集合幂级数】【FWT】【DP】

    Description 你有一个随机数生成器,它会以一定的概率生成[0,2^N-1]中的数,每一个数的概率是由序列A给定的,Pi=Ai/sum(Ai) 现在有一个初始为0的数X,每一轮随机生成一个数v ...

  8. matplotlib中plt.scatter()参数详解

    scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, l ...

  9. Java indexOf() 方法

    indexOf() 方法有以下四种形式: public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1. public ...

  10. 客户端框架-MVC

    MVC Model-View-Controller MVC是比较直观的架构模式,用户操作->View(负责接收用户的输入操作)->Controller(业务逻辑处理)->Model( ...