如何在線程中獲取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}

相關文章
相關標籤/搜索