本文介绍了Spring 多线程下注入bean问题详解,分享给大家,具体如下:
问题
Spring中多线程注入userThreadService注不进去,显示userThreadService为null异常
代码如下:
public class UserThreadTask implements Runnable {
@Autowired
private UserThreadService userThreadService;
@Override
public void run() {
AdeUser user = userThreadService.get("0");
System.out.println(user);
}
}
解决方案一
把要注入的Service,通过构造传过去,代码如下:
public class UserThreadTask implements Runnable {
private UserThreadService userThreadService;
public UserThreadTask(UserThreadService userThreadService) {
this.userThreadService = userThreadService;
}
@Override
public void run() {
AdeUser user = userThreadService.get("0");
System.out.println(user);
}
}
Thread t = new Thread(new UserThreadTask(userThreadService));
t.start();
解决方案二
通过ApplicationContext中获取需要使用的Service
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
ApplicationContextHolder.context = context;
}
//根据bean name 获取实例
public static Object getBeanByName(String beanName) {
if (beanName == null || context == null) {
return null;
}
return context.getBean(beanName);
}
//只适合一个class只被定义一次的bean(也就是说,根据class不能匹配出多个该class的实例)
public static Object getBeanByType(Class clazz) {
if (clazz == null || context == null) {
return null;
}
return context.getBean(clazz);
}
public static String[] getBeanDefinitionNames() {
return context.getBeanDefinitionNames();
}
}
Spring 加载自己定义的ApplicationContextHolder类
<bean class = "cn.com.infcn.applicationcontext.ApplicationContextHolder"></bean>
根据 bean 的名称获取实例
UserService user = (UserService) ApplicationContextHolder.getBeanByName("userService");
根据 bean 的Class 获取实例(如果该Class存在多个实例,会报错的)
UserService user = (UserService) ApplicationContextHolder.getBeanByType(UserService.class);
这种方式,不管是否多线程,还是普通的不收spring管理的类,都可以使用该方法获得spring管理的bean。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。
(jijs)
原文链接:http://www.jianshu.com/p/c8a43d26bc0f?utm_source=tuicool&utm_medium=referral
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。