Springboot @Component下@Autowired的注入為null【轉】
標簽(空格分隔): Spring
https://zakariyya.github.io/2018/08/23/backEnd-spring-springboot-Component下-Autowired的注入為null/
自定義類時,出現@Autowired下的層出現空指針異常。
背景
做了一個TCP服務器來接入智能設備,然后需要將設備實時發送的定位等關鍵信息存儲到數據庫。為了考慮將來可能對外提供rest接口,采用將TCP服務器集成到SpringBoot框架,當然,也是為了能最快利用mybatis框架實現數據訪問,然后依次解決了如何啟動,如何注銷等各種問題,然后在TCP服務器消息處理時,需要寫數據庫,直接調用DAO層,編譯報錯。改為調用Service層,編譯正常,運行到調用的地方,報空指針異常,跟蹤到異常位置,發現service為空,也就是按照之前controller層通過@Autowired注入service層失效。
解決方案
@Component
public class ServerHandler extends IoHandlerAdapter {
@Autowired
protected HealthDataService healthDataService;
private static ServerHandler serverHandler ;
@PostConstruct //通過@PostConstruct實現初始化bean之前進行的操作
public void init() {
serverHandler = this;
serverHandler.healthDataService = this.healthDataService;
// 初使化時將已靜態化的testService實例化
}
//測試調用
public void test(){
serverHandler .healthDataService.你的service層方法;
//
}
說明
將需要調用Spring的Service層的類通過@Component注解為組件加載;
同樣通過@Autowired獲取Service層的Bean對象;
為類聲明一個靜態變量,方便下一步存儲bean對象;
划重點:通過注解 @PostConstruct ,在初始化的時候初始化靜態對象和它的靜態成員變量healthDataService,原理是拿到service層bean對象,靜態存儲下來,防止被釋放。
那些趟過的坑
剛開始調用的時候,總覺得很簡單,以前springmvc寫個配置,將對象標注為bean就可以隨意調用Spring IOC容器的beans了,但是這是SpringBoot,估計還是有區別,依次試驗了百度出來的前三頁幫助,基本沒有成功的。包括:
將工具類申明為spring組件,如@controller @compent 等,在spring自動掃描包設置中將工具類所在的包加進來; 無效
new一個service; 無效;
等等!