本文介绍了Spring 多线程下注入bean问题详解,分享给你们,具体以下:java
问题spring
Spring中多线程注入userThreadService注不进去,显示userThreadService为null异常多线程
代码以下:app
public class UserThreadTask implements Runnable { @Autowired private UserThreadService userThreadService; @Override public void run() { AdeUser user = userThreadService.get("0"); System.out.println(user); } }
解决方案一ide
把要注入的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();
解决方案二this
经过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类code
<bean class = "cn.com.infcn.applicationcontext.ApplicationContextHolder"></bean>
根据 bean 的名称获取实例xml
UserService user = (UserService) ApplicationContextHolder.getBeanByName("userService");
根据 bean 的Class 获取实例(若是该Class存在多个实例,会报错的)
UserService user = (UserService) ApplicationContextHolder.getBeanByType(UserService.class);
这种方式,无论是否多线程,仍是普通的不收spring管理的类,均可以使用该方法得到spring管理的bean。
以上就是本文的所有内容,但愿对你们的学习有所帮助,也但愿你们多多支持脚本之家。