一个 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源点
注意:本文归作者所有,未经作者允许,不得转载