欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot 多線程處理任務(wù) 無(wú)法@Autowired注入bean問(wèn)題解決

 更新時(shí)間:2019年06月06日 11:07:58   作者:EVAO_大個(gè)子  
這篇文章主要介紹了詳解SpringBoot 多線程處理任務(wù) 無(wú)法@Autowired注入bean問(wèn)題解決,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

在多線程處理問(wèn)題時(shí),無(wú)法通過(guò)@Autowired注入bean,報(bào)空指針異常,

在線程中為了線程安全,是防注入的,如果要用到這個(gè)類,只能從bean工廠里拿個(gè)實(shí)例。

解決方法如下:

1.創(chuàng)建一個(gè)工具類代碼:

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對(duì)象的工具類
 * @Author: yaorong
 * @CreateDate: 2018/12/10
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {
  /**
   * 上下文對(duì)象實(shí)例
   */
  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
  }

  /**
   * 獲取applicationContext
   *
   * @return
   */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  /**
   * 通過(guò)name獲取 Bean.
   *
   * @param name
   * @return
   */
  public static Object getBean(String name) {
    return getApplicationContext().getBean(name);
  }

  /**
   * 通過(guò)class獲取Bean.
   *
   * @param clazz
   * @param <T>
   * @return
   */
  public static <T> T getBean(Class<T> clazz) {
    return getApplicationContext().getBean(clazz);
  }

  /**
   * 通過(guò)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);
  }

}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論