Springboot 定時任務,service層無法注入問題詳細解決


開發一個微信小程序后台,建立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");

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM