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开始提取子串 ${ ...
随机推荐
- 第二课丶pygame
学号:2017*****1024 姓名:王劲松 我的码云贪吃蛇项目仓库:https://gitee.com/Danieljs/sesnake 分析游戏中的备注和问题:10分钟 游戏名称.分数改动:3分 ...
- Java基础学习-流程控制语句
在一个程序执行的过程中,各条语句的执行顺序对程序的结果是有直接影响的.也就是说程序的流程对运行结果有直接的影响.所以,我们必须清楚每条语句的执行流程.而且,很多时候我们要通过控制语句的执行顺序来实现我 ...
- xueping wang 记录2
在使用easyui的tabs的时候, 标签页上的 可关闭 按钮 显示不出来? tabs的 closable:true 属性, 实际上是通过在 标签头 tabHeader 中的最后面, 添加一个超链接 ...
- SQL 删除数据 的所有用法
https://blog.51cto.com/13588598/2066335 1.使用 delete 语句删除表中的数据:语法:delete from <表名> [where <删 ...
- Jvm类的加载机制
1.概述 虚拟机加载Class文件(二进制字节流)到内存,并对数据进行校验.转换解析和初始化,最终形成可被虚拟机直接使用的Java类型,这一系列过程就是类的加载机制. 2.类的加载时机 类从被虚拟机加 ...
- 四、ConcurrentHashMap 锁分段机制
回顾: HashMap与Hashtable的底层都是哈希表,但是 HashMap:线程不安全 Hashtable:线程安全,但是效率非常低,且存在[复合操作](如"若存在则删除") ...
- BeanUtils的copyproPerties方法的用法
转自:Hassan Blog的博客 一.简介: BeanUtils提供对Java反射和自省API的包装.其主要目的是利用反射机制对JavaBean的属性进行处理.我们知道,一个JavaBean通常包 ...
- script 修改 plist遇到的问题
一个sh脚本每次build的时候动态修改info.plist文件 达到动态更改版本号的目的 但是估计是因为缓存的缘故 每次只有clean之后再运行才会修改成功 看script执行的log 好像是先修改 ...
- 在action中进行文件下载,下载时运行不报错,可是也不下载
在写前端下载页面时,使用ajax方式调用action中的方法,然后就将下载内容返回js中了,所以没有下载,之后改为使用Windows.location进行下载,就没有问题了. action中代码: i ...
- .NET Core WEB API使用Swagger生成在线接口文档
1项目引用Swashbuckle.AspNetCore程序集和Microsoft.Extensions.PlatformAbstractions程序集 右击项目打开"管理NuGet程序包.. ...