java 多线程bean 注入_Spring 多线程下注入bean问题详解

本文详细探讨了在Spring多线程环境下bean注入失败的问题,并提供了两种解决方法:通过构造函数传递Service实例和利用ApplicationContext获取bean。通过ApplicationContext创建线程安全的方式来获取和使用Spring管理的bean,适用于各种场景。
摘要由CSDN通过智能技术生成

本文介绍了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 的名称获取实例

UserService user = (UserService) ApplicationContextHolder.getBeanByName("userService");

根据 bean 的Class 获取实例(如果该Class存在多个实例,会报错的)

UserService user = (UserService) ApplicationContextHolder.getBeanByType(UserService.class);

这种方式,不管是否多线程,还是普通的不收spring管理的类,都可以使用该方法获得spring管理的bean。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

相关文章

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值