当前位置:主页 > 软件编程 > JAVA代码 >

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

时间:2020-10-07 14:25:48 | 栏目:JAVA代码 | 点击:

在多线程处理问题时,无法通过@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);
  }

}

您可能感兴趣的文章:

相关文章