今天因为项目需要Quartz任务调度实现定时查询数据库商品的库存问题,且生成Excel文件保存在指定WEB目录下!这就出现一个问题!要在Quartz中访问javaEE的API得到WEB的路径,同时又要能从Spring中getBean进行数据操作的调用,百度了一下!都没有找到相关的很好的解决方案!然后查阅了下SpringAPI,发现了一个很好的解决方案。

    

    在Spring与WEB容器整合时会用到ContextLoaderListener监听器,源码如下:

  public class ContextLoaderListener extends ContextLoader
       implements ServletContextListener {
      
        public ContextLoaderListener(WebApplicationContext context) {
            super(context);
        }
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            initWebApplicationContext(event.getServletContext());
        }
        
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            closeWebApplicationContext(event.getServletContext());
            ContextCleanupListener.cleanupAttributes(event.getServletContext());
        }
    
    }


     查看源码大概可以知道,在WEB容器启动的时候会运行其中contextInitialized()方法!后调用

initWebApplicationContext(event.getServletContext());得到初始化WebApplicationContext。

WebApplicationContext的源码:

public interface WebApplicationContext extends ApplicationContext {

        ServletContext getServletContext();
}


因此我们可以通过WebApplicationContext的实现类就可得到ServletContext;如下:

ServletContext  servletContext=(ServletContext)ContextLoader
                                                .getCurrentWebApplicationContext()
                                                .getServletContext();


其中的ContextLoader.getCurrentWebApplicationContext()返回的是WebApplicationContext,因为此类继承了ApplicationContext,所以我们也可以通过getBean(),在Spring容器中取到由Spring容器管理的对象,