当前位置: 移动技术网 > IT编程>开发语言>Java > Spring 多线程下注入bean问题详解

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网