springboot springmvc 定時器 定時任務 task 中獲取 servletContext

springmvc,springboot 定時器 定時任務 task 中獲取 servletContext,代碼如下,通過 @Autowired 注入 servletContext。

@Component
public class MyTask {
    private static final Logger logger = LoggerFactory.getLogger(MyTask.class);
    @Autowired
    private ServletContext servletContext;

    // 秒 分 時 日 月 周
    @Scheduled(cron = "0 * * * * *")
    public void resetDays() {
        if (servletContext == null) {
            logger.info("未獲取到:servletContext");
            return;
        }

        logger.info("已獲取到:servletContext");
    }
}

提示,task 中不能用 ContextLoader.getCurrentWebApplicationContext() 的方式獲取 servletContext,獲取不到。

參考:http://www.fengyunxiao.cn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章