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开始提取子串 ${ ...
随机推荐
- continue #结束本次循环,继续下一次代码
for i in range(10): if i <5: continue print(i) for j in range(10): pr ...
- JS构造函数、原型对象、隐含参数this
This 解析器再调用函数每次都会向函数内部传递一个隐含的参数this,this指向的是一个对象(函数执行的上下文对象) 1.以函数形式调用时,this永远是window. 2.以方法形式调用时,th ...
- Go-For Range 性能研究
文章转载地址:https://www.flysnow.org/2018/10/20/golang-for-range-slice-map.html 如果我们要遍历某个数组,Map 集合.Slice 切 ...
- 【搬运工】linux下创建用户(一)
转载:http://www.cnblogs.com/ylan2009/articles/2321177.html linux下创建用户(一) Linux 系统是一个多用户多任务的分时操作系统,任何一个 ...
- Jmeter 常见错误
常见错误 https://testerhome.com/topics/10950 接口测试 https://blog.csdn.net/github_27109687/article/details/ ...
- 7_linux用户及权限(2)和管理
useradd:useradd [options] USERNAME -u UID -g GID(基本组) -G GID,...(附加组) //省略号表示可以有多个,彼此之间用逗号隔开 -c &quo ...
- Linux下安装docker
//安装docker //需要输入时 输y就可以yum install -y epel-releaseyum install docker-io # 加入开机启动chkconfig docker on ...
- Day 4 变量常量
编辑语言的分类 编程语言,他是人与计算机沟通的一种介质 机器语言 计算机只认识0和1,为了和计算机沟通,你也得认识0和1 优点:执行效率快 缺点:普通人根本就写不了这种代码,开发效率低 汇编语言 他还 ...
- java mvn:安装jar包
mvn install:install-file -Dfile=fastdfs-client-java-1.27-SNAPSHOT.jar(路径) -DgroupId=org.csource -Dar ...
- windows,用c++调用mxnet做前向
参考博客: https://blog.csdn.net/qq_34062105/article/details/82590553 https://blog.csdn.net/u012234115/ar ...