解決方案:
1.上代碼
@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層方法>;
}
2.說明:
將需要調用Spring的Service層的類通過@Component註解爲組件加載;
同樣通過@Autowired獲取Service層的Bean對象;
爲類聲明一個靜態變量,方便下一步存儲bean對象;
劃重點:通過註解@PostConstruct ,在初始化的時候初始化靜態對象和它的靜態成員變量healthDataService,原理是拿到service層bean對象,靜態存儲下來,防止被釋放。
那些趟過的坑:
剛開始調用的時候,總覺得很簡單,以前springmvc寫個配置,將對象標註爲bean就可以隨意調用Spring IOC容器的beans了,但是這是SpringBoot,估計還是有區別,一次試驗了百度出來的前三頁幫助,基本沒有成功的。包括:
1)將工具類申明爲spring組件,如@controller @compent 等,在spring自動掃描包設置中將工具類所在的包加進來; 無效
2)new一個service; 無效;
等等!
原文:https://blog.csdn.net/georgeshaw1/article/details/74943089