详解SpringBoot 多线程处理任务 无法@Autowired注入bean问题解决

  • 2022-07-20 18:50:38

在多线程处理问题时,无法通过@autowired注入bean,报空指针异常,

在线程中为了线程安全,是防注入的,如果要用到这个类,只能从bean工厂里拿个实例。

解决方法如下:

1.创建一个工具类代码:

package com.hqgd.pms.common;

import org.springframework.beans.beansexception;
import org.springframework.context.applicationcontext;
import org.springframework.context.applicationcontextaware;
import org.springframework.stereotype.component;

/**
 * @description: 获取bean对象的工具类
 * @author: yaorong
 * @createdate: 2018/12/10
 */

@component
public class springcontextutil implements applicationcontextaware {
  /**
   * 上下文对象实例
   */
  private static applicationcontext applicationcontext;

  @override
  public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
    springcontextutil.applicationcontext = applicationcontext;
  }

  /**
   * 获取applicationcontext
   *
   * @return
   */
  public static applicationcontext getapplicationcontext() {
    return applicationcontext;
  }

  /**
   * 通过name获取 bean.
   *
   * @param name
   * @return
   */
  public static object getbean(string name) {
    return getapplicationcontext().getbean(name);
  }

  /**
   * 通过class获取bean.
   *
   * @param clazz
   * @param <t>
   * @return
   */
  public static <t> t getbean(class<t> clazz) {
    return getapplicationcontext().getbean(clazz);
  }

  /**
   * 通过name,以及clazz返回指定的bean
   *
   * @param name
   * @param clazz
   * @param <t>
   * @return
   */
  public static <t> t getbean(string name, class<t> clazz) {
    return getapplicationcontext().getbean(name, clazz);
  }
}

2.使用方法

@slf4j
@service
public class serialportservice {
  public static serialport mserialport = null;
//  private simpmessagingtemplate simpmessage;
  private dataacquisitionservice das;
  private systemservice systemservice;
  private sysparammapper sysparammapper;

  public serialportservice() {
    this.das = springcontextutil.getbean(dataacquisitionservice.class);
    this.systemservice = springcontextutil.getbean(systemservice.class);
    this.sysparammapper = springcontextutil.getbean(sysparammapper.class);
  }

}

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

猜你喜欢