多线程并发系列(二):在多线程中注入SpringBean

star2017 1年前 ⋅ 514 阅读

一个 Web 项目的Socket需用到多线程,每一个连接创建一条线程来处理数据。
在多线程中需要用到 Spring 中的 Bean,如果直接用 Spring 注入是会报NullPointerException错误。原因是线程类无法提前委托给Spring管理,是在使用中创建的。

工具类

创建一个获取Bean的工具类,获取ApplicationContext

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }    

     // 获取对象 这里重写了bean方法,起主要作用         
    @SuppressWarnings("unchecked")
    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());
    }
}

工具类交给Spring管理

<!-- 注册Spring工具类 -->
<bean id="springContextUtil" class="com.commons.SpringContextUtil" ></bean>

在线程中获取业务Bean

public class ThreadSocket implements Runnable {
    private DeviceService deviceService = SpringContextUtil.getBean("deviceServiceImpl");
    private GoodsService goodsService = SpringContextUtil.getBean("goodsServiceImpl");

    ........

}
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: