如何在线程中获取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(); }