本文介紹了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。
以上就是本文的所有內容,但願對你們的學習有所幫助,也但願你們多多支持腳本之家。