Java Spring 在线程中或其他位置获取 ApplicationContext 或 ServiceBean
部分一转载自:http://blog.csdn.net/yang123111/article/details/32099329
via @yang123111
部分二转载自:http://www.cnblogs.com/20160813main/p/5826446.html
via @Chell
获取Spring的上下文环境ApplicationContext的方式
Web项目中发现有人如此获得spring的上下环境:
public class SpringUtil {
public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
public static Object getBean(String serviceName){
return context.getBean(serviceName);
}
}
在web项目中这种方式非常不可取!!!
分析:
首先,主要意图就是获得Spring上下文;
其次,有了Spring上下文,希望通过getBean()方法获得Spring管理的Bean的对象;
最后,为了方便调用,把上下文定义为static变量或者getBean方法定义为static方法;
但是,在web项目中,系统一旦启动,web服务器会初始化Spring的上下文的,我们可以很优雅的获得Spring的ApplicationContext对象。
如果使用
new ClassPathXmlApplicationContext("applicationContext.xml");
相当于重新初始化一遍!!!!
也就是说,重复做启动时候的初始化工作,第一次执行该类的时候会非常耗时!!!!!
正确的做法是:
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文环境
/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
*通过传递applicationContext参数初始化成员变量applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
}
注意:这个地方使用了Spring的注解@Component,如果不是使用annotation的方式,而是使用xml的方式管理Bean,记得写入配置文件
<bean id="springContextUtil" class="com.ecdatainfo.util.SpringContextUtil" singleton="true" />
其实
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
这种方式获取Sping上下文环境,最主要是在测试环境中使用,比如写一个测试类,系统不启动的情况下手动初始化Spring上下文再获取对象!
*******************************************************************************************************************************************
如果想要在run()方法中调用dao层或者service层,常规的方法应该是这样
public class ServerStatusWatcherThread extends Thread {
@Resource(name="servermanageDao")
ServerManagementMapper servermanageDao;
@Autowired
ServerManagementService serverservice;
@Override
public void run(){
List<ServerManagementItem> servers =servermanageDao.getAll();
serverservice.QuerySOSServer();
//what do you want to do please write here
}
}
结果会报如下异常:Exception in thread "Thread-3" java.lang.NullPointerException
解决方法可以用getBean的方式来解决这个问题,异常解决
public class ServerStatusWatcherThread extends Thread {
//@Resource(name="servermanageDao")
//ServerManagementMapper servermanageDao;
//改成
ServerManagementMapper servermanageDao=(ServerManagementMapper) SpringContextUtil.getBean("servermanageDao");
//@Autowired
//ServerManagementService serverservice;
//改成:
ServerManagementService servemanagementService=(ServerManagementService) SpringContextUtil.getBean("servemanagementService");
@Override
public void run(){
List<ServerManagementItem> servers =servermanageDao.getAll();
serverservice.QuerySOSServer();
//what do you want to do please write here
}
}
Java Spring 在线程中或其他位置获取 ApplicationContext 或 ServiceBean的更多相关文章
- 解决 spring boot 线程中使用@Autowired注入Bean的方法,报java.lang.NullPointerException异常
问题描述 在开发中,因某些业务逻辑执行时间太长,我们常使用线程来实现.常规服务实现类中,使用 @Autowired 来注入Bean,来调用其中的方法.但如果在线程类中使用@Autowired注入的Be ...
- 一文搞懂Java/Spring/Dubbo框架中的SPI机制
几天前和一位前辈聊起了Spring技术,大佬突然说了SPI,作为一个熟练使用Spring的民工,心中一紧,咱也不敢说不懂,而是在聊完之后赶紧打开了浏览器,开始的学习之路,所以也就有了这篇文章.废话不多 ...
- 解决Spring在线程中注入为空指针的问题
在启用线程中使用来jdbcTemplate来查询数据库,引入jdbcTemplate是用Spring @Autowired注解 方式引入,但是在运行中 jdbcTemplate 总是 空指针 解决 ...
- 通过spring,在项目的任意位置获取当前Request
需要引入: import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.R ...
- Java核心知识点 --- 线程中如何创建锁和使用锁 Lock , 设计一个缓存系统
理论知识很枯燥,但这些都是基本功,学完可能会忘,但等用的时候,会发觉之前的学习是非常有意义的,学习线程就是这样子的. 1.如何创建锁? Lock lock = new ReentrantLock(); ...
- java android 将 List中元素互换位置
很多时候我要对List中的元素调换位置,这时候可以用如下代码,意思是将data中的index1与index2元素互换位置 //data 为List Collections.swap(data,inde ...
- Java在不同线程中运行代码
start()方法开始为一个线程分配CPU时间,这导致对run()方法的调用. 代码1 package Threads; /** * Created by Frank */ public class ...
- spring mvc Controller中使用@Value无法获取属性值
在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...
- shell 字符串中定位字符位置 获取字符位置
linux shell 字符串操作(长度,查找,替换)详解 该博文中描述的如下两个字符串操作, ${string:position} #在$string中, 从位置$position开始提取子串 ${ ...
随机推荐
- python2 与 python3的区别
python2 与 python3的区别 几乎所有的python2程序都需要一些修改才能正常的运行在python3的环境下.为了简化这个转换过程,Python3自带了一个2to3的实用脚本.这个脚本会 ...
- Python连接redis时要注意的点
一.一般连接redis情况 from redis import Redis # 实例化redis对象 rdb = Redis(host='localhost', port=6379, db=0) rd ...
- sublime text 3安装
输入快捷键:shift+ctrl+p, 打开安装界面,先要安装install package control,然后选择install package. 增加编译环境,ctrl + b 执行. 安装如下 ...
- Maven pom详解
POM全称是Project Object Model,即项目对象模型.pom.xml是maven的项目描述文件,以xml的 形式描述项目的信息,包括项目名称.版本.项目id.项目的依赖关系.编译环境. ...
- Xilinx Vivado的使用详细介绍(4):Zedboard+vivado之流水灯(加SDK)
Vivado+zedboard之初学流水灯 Author:zhangxianhe 环境:vivado 2016.3(已验证适用于2015.4) 开发板:Zedboard version xc7z020 ...
- 为wordpress后台登陆添加算术验证码
对于新建站(个人博客-柠檬https://ninmong.com)的站长来说提高后台的安全性,是一件非常重要的事,添加验证可以起到很好的效果,废话少说,贴代码 //后台登陆数学验证码 function ...
- angular + socket.io+nodejs
一.服务器端: 基本和nodejs工程相同 https://www.cnblogs.com/xuanmanstein/p/10509445.html 安装socket.io npm i --save ...
- vim实现实时自动保存
进https://www.vim.org/scripts/script.php?script_id=4521网站下载vim -auto-save wget https://www.vim.org/s ...
- NetSec2019 20165327 Exp2 后门原理与实践
NetSec2019 20165327 Exp2 后门原理与实践 快速找到重点: (1)使用netcat获取主机操作Shell,cron启动 (0.5分) (2)使用socat获取主机操作Shell, ...
- Subversion ----> svnserve.conf / authz / passwd / hooks-env.tmpl <<翻译笔记>>
svnserve.conf 假如你使用这个文件去允许访问这个仓库,那么这个文件控制着svnserve后台进程的配置.(但是如果你只是允许通过http和/或者 file:URLs,则这个文件就不起作用了 ...