這篇文章主要介紹了SpringBoot多線程處理任務無法@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;
@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);
}
}感謝你能夠認真閱讀完這篇文章,希望小編分享的“SpringBoot多線程處理任務無法@Autowired注入bean怎么辦”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。