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

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();
    }

 

posted @ 2017-09-15 10:40  想看名字有多长  阅读(298)  评论(0编辑  收藏  举报