springmvc springboot 定时器 定时任务 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

猜你喜欢

转载自blog.csdn.net/m0_37202351/article/details/86231337