Spring 多线程下注入bean问题详解
本文介绍了Spring多线程下注入bean问题详解,分享给大家,具体如下:
问题
Spring中多线程注入userThreadService注不进去,显示userThreadService为null异常
代码如下:
publicclassUserThreadTaskimplementsRunnable{
@Autowired
privateUserThreadServiceuserThreadService;
@Override
publicvoidrun(){
AdeUseruser=userThreadService.get("0");
System.out.println(user);
}
}
解决方案一
把要注入的Service,通过构造传过去,代码如下:
publicclassUserThreadTaskimplementsRunnable{
privateUserThreadServiceuserThreadService;
publicUserThreadTask(UserThreadServiceuserThreadService){
this.userThreadService=userThreadService;
}
@Override
publicvoidrun(){
AdeUseruser=userThreadService.get("0");
System.out.println(user);
}
}
Threadt=newThread(newUserThreadTask(userThreadService)); t.start();
解决方案二
通过ApplicationContext中获取需要使用的Service
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
publicclassApplicationContextHolderimplementsApplicationContextAware{
privatestaticApplicationContextcontext;
@Override
publicvoidsetApplicationContext(ApplicationContextcontext)throwsBeansException{
ApplicationContextHolder.context=context;
}
//根据beanname获取实例
publicstaticObjectgetBeanByName(StringbeanName){
if(beanName==null||context==null){
returnnull;
}
returncontext.getBean(beanName);
}
//只适合一个class只被定义一次的bean(也就是说,根据class不能匹配出多个该class的实例)
publicstaticObjectgetBeanByType(Classclazz){
if(clazz==null||context==null){
returnnull;
}
returncontext.getBean(clazz);
}
publicstaticString[]getBeanDefinitionNames(){
returncontext.getBeanDefinitionNames();
}
}
Spring加载自己定义的ApplicationContextHolder类
根据bean的名称获取实例
UserServiceuser=(UserService)ApplicationContextHolder.getBeanByName("userService");
根据bean的Class获取实例(如果该Class存在多个实例,会报错的)
UserServiceuser=(UserService)ApplicationContextHolder.getBeanByType(UserService.class);
这种方式,不管是否多线程,还是普通的不收spring管理的类,都可以使用该方法获得spring管理的bean。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 孙子生日祝福语短句简短
11 对老人新年祝福语简短
12 新郎朋友红包祝福语简短
13 升学了祝福语简短句
14 物业小区高考祝福语简短
15 简短经典的祖国祝福语
16 新年祝福语大全 简短情侣
17 生日祝福语对妈妈简短
18 新年简短祝福语给亲人