spring定时任务中使用servletContext

     关于spring的定时任务的相关配置不作相关的说明了,官方文档写的很清楚,网上也有不少不少人的配置详解。但我以为你下的哪一个版本的spring就按照那个相关的文档去配置比较好一点。 web

     其实纠结的不是spring定时任务,而是定时任务中要用到servletContext对象,由于项目中用到全文检索,要在午夜时分干一些事情。现总结两种思路,以防忘记。但有一种在使用过程当中跑挂了,不明白,另外一种正在测试! spring

1:使用ServletContextListener。

    监听器通常都用过吧。对,就是用监听器完成初始化工做。当web服务器启动后就给spring的定时任务中注入ServletContext对象。 服务器

    在定时任务中会有这样的属性和方法: app

    private static ServletContext application;set,get略! 测试

    而后在监听器contextInitialized(ServletContextEvent arg0)方法中使用set方法给servletContext对象赋值。这样你就能够在你的定时任务的方法中用servletContext对象了。 this

2:实现ServletContextAware接口

    这种方法我建议使用:先看一下这个接口的注释吧! spa

接口上的注释: .net

  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对象是否是很方便!!

相关文章
相关标签/搜索