其他分享
首页 > 其他分享> > 解决:在多线程处理问题时,无法通过@Autowired注入bean,报空指针异常

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

作者:互联网

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

}

 

标签:applicationContext,return,name,Autowired,getBean,param,bean,多线程,public
来源: https://www.cnblogs.com/tszr/p/16387393.html