关于spring的定时任务的相关配置不做相关的说明了,官方文档写的很清楚,网上也有很多很多人的配置详解。但我觉得你下的哪个版本的spring就按照那个相关的文档去配置比较好一点。
其实纠结的不是spring定时任务,而是定时任务中要用到servletContext对象,因为项目中用到全文检索,要在午夜时分干一些事情。现总结两种思路,以防忘记。但有一种在使用过程中跑挂了,不明白,另一种正在测试!
1:使用ServletContextListener。
监听器一般都用过吧。对,就是用监听器完成初始化工作。当web服务器启动后就给spring的定时任务中注入ServletContext对象。
在定时任务中会有这样的属性和方法:
private static ServletContext application;set,get略!
然后在监听器contextInitialized(ServletContextEvent arg0)方法中使用set方法给servletContext对象赋值。这样你就可以在你的定时任务的方法中用servletContext对象了。
2:实现ServletContextAware接口
这种方法我建议使用:先看一下这个接口的注释吧!
接口上的注释:
Interface to be implemented by any object that wishes to be notified of the {@link ServletContext} (typically determined by the {@link WebApplicationContext}) that it runs in.
方法上的注释:
Set the {@link ServletContext} that this object runs in.我想这已经很明白了吧!只要继承了这个接口在方法setServletContext(ServletContext servletContext);中就可以得到想要的serlvetContext对象。
即我们不用在控制层用request来到servletContext对象了。在任何方法上只要实现了这个接口就可以得到servletContext对象是不是很方便!!