如何在線程中獲取spring 管理的bean


轉載自:https://my.oschina.net/skyline520/blog/181158?fromerr=GjtR6Wec

spring xml中定義 

<!--spring 工具類-->
    <bean id="springContextUtil" class="com.skyline.pub.utils.SpringContextUtil"/>

SpringContextUtil的代碼如下

 

package com.skyline.pub.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Locale;

/**
 * Spring 獲取 bean工具類
 * Author: skyline{http://my.oschina.net/skyline520}
 * Created: 13-6-12 上午7:44
 */
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public static <T> T getBean(String beanName){
        return (T) context.getBean(beanName);
    }

    public static String getMessage(String key){
        return context.getMessage(key, null, Locale.getDefault());
    }

}

 

然后在線程中直接使用 (注: uploadService 為spring 中配置的bean)

 

@Override
    public void run() {
        UploadService uploadService = SpringContextUtil.getBean("uploadService");
        switch (sheetIndex){
            case 1:uploadService.updateMiddleSaleProcedure(start,limit); break;
            case 2:uploadService.updateProductCountProcedure();break;
            case 3:uploadService.updateMonthProcedure();break;
        }
        countDownLatch.countDown();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM