如何在线程中获取spring 管理的bean

需求:在Action中启动一个Thread去作一件事,因项目是经过spring的自动注入的Bean以前的依赖关系,在线程中的Service引用始终没法获得对象,即便是new出来的,可Service中的Dao引用又是null的。java


方法一:用Spring的方法获取到当前的容器(也是当前应用下惟一的spring容器),并从中获取资源。spring


参考代码1:数据库

  WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();app

  IService service = (IService) context.getBean("service");ide


参考代码2:工具

spring xml中定义 this

1<!--spring 工具类-->spa

2<beanid="springContextUtil"class="com.skyline.pub.utils.SpringContextUtil"/>.net

SpringContextUtil的代码以下 线程

01packagecom.skyline.pub.utils;

02

03importorg.springframework.beans.BeansException;

04importorg.springframework.context.ApplicationContext;

05importorg.springframework.context.ApplicationContextAware;

06

07importjava.util.Locale;

08

09/**

10* Spring 获取 bean工具类

11* Author: skyline{http://my.oschina.net/skyline520}

12* Created: 13-6-12 上午7:44

13*/

14publicclassSpringContextUtil implementsApplicationContextAware {

15

16privatestaticApplicationContext context = null;

17publicvoidsetApplicationContext(ApplicationContext applicationContext) throwsBeansException {

18this.context = applicationContext;

19}

20

21publicstatic<T> T getBean(String beanName){

22return(T) context.getBean(beanName);

23}

24

25publicstaticString getMessage(String key){

26returncontext.getMessage(key, null, Locale.getDefault());

27}

28

29}

而后在线程中直接使用 (注: uploadService 为spring 中配置的bean)

01@Override


02publicvoidrun() {

03UploadService uploadService = SpringContextUtil.getBean("uploadService");

04switch(sheetIndex){

05case1:uploadService.updateMiddleSaleProcedure(start,limit); break;

06case2:uploadService.updateProductCountProcedure();break;

07case3:uploadService.updateMonthProcedure();break;

08}

09countDownLatch.countDown();

10}


方法二:能够经过在Action中建立Thread的时候把Action中的service引用做为构造参数传递给Thread,这样Thread中的Service对象就是经过SPring的自动注入获得的了。

01packagecom.skyline.upload.listener;

02

03importorg.springframework.beans.factory.InitializingBean;

04

05/**

06* 这个类能够注入一些 dao 工具类

07* 在 afterPropertiesSet 方法中执行数据库链接级别的操做

08* Author: skyline{http://my.oschina.net/skyline520}

09* Created: 13-6-12 下午7:41

10*/

11publicclassUploadOnLoadListener implementsInitializingBean {

12

13privateCommandTextService commandTextService;

14

15publicvoidsetCommandTextService(CommandTextService commandTextService) {

16this.commandTextService = commandTextService;

17}

18

19publicvoidclose(){

20}

21publicvoidafterPropertiesSet() throwsException {

22//在这里启动你的线程

23//方式1 利用构造方法把bean传递过去

24newThread(commandTextService);

25//方式2 在thread 内部使用我以前说的获取bean的方式

26newThread();

27}

28}

相关文章
相关标签/搜索