Spring 多线程注入bean Spring 多线程下注入bean问题详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring 多线程注入bean Spring 多线程下注入bean问题详解

jijs   2021-03-29 我要评论
想了解Spring 多线程下注入bean问题详解的相关内容吗,jijs在本文为您仔细讲解Spring 多线程注入bean的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,多线程注入bean,spring,多线程,bean,spring,注入bean,下面大家一起来学习吧。

本文介绍了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 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。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们