開發一個微信小程序后台,建立websocket 長連接,需要后台開啟定時任務,
定時任務定時查庫,相應前台
但是具體執行過程中一直在報空指針錯誤,最后定位到service 為空,無法調用其相關的方法導致的
於是我嘗試不用@Autowired 注入實例,自己new ,但是還是失敗了,報空指針
這是spring的一個Bug ,需要手動去配置一個類,主動獲取實例,在定時任務中(繼承TimerTask類),@Autowired 是失效的,無法注入
解決方案如下:
1.首先添加一個工具類,就是application
應注意,同樣需要注入添加 @Compent注解
package com.cskaoyan.carparking.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; /** * @Auther: YangTao * @Date: 2019/2/21 0021 * 配置類,解決定時任務無法注入的問題 */ @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); }
2.在我們的servcie的實現類注解添加名字,以便我們獲取
3.我們在需要的定時任務類中獲取service實例就可以使用了
StopService stopService = (StopService) ApplicationContextUtil.getBean("myService");