當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 多线程下注入bean问题
生活随笔
收集整理的這篇文章主要介紹了
Spring 多线程下注入bean问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
Spring中多線程注入userThreadService注不進去,顯示userThreadService為null異常
代碼如下:
解決方案一
把要注入的Service,通過構造傳過去,代碼如下:
public class UserThreadTask implements Runnable {private UserThreadService userThreadService;public UserThreadTask(UserThreadService userThreadService) {this.userThreadService = userThreadService;}@Overridepublic 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;@Overridepublic 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。
想了解更多精彩內容請關注我的公眾號
本人簡書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點擊這里快速進入簡書
GIT地址:http://git.oschina.net/brucekankan/
點擊這里快速進入GIT
總結
以上是生活随笔為你收集整理的Spring 多线程下注入bean问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring mvc HTTP协议之缓存
- 下一篇: Spring mvc 启动配置文件加载两