菜鸟之路——Spring MVC(十一)ContextLoaderListener加载配置文件

来源:互联网 发布:js div跟随滚动条滑动 编辑:程序博客网 时间:2024/06/09 16:16

  ContextLoaderListener的作用:在启动Web容器时,自动装配Spring applicationContext.xml的配置信息。

因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。

//实现了接口ServletContextListener,也就是说他必须实现contextDestroyed, contextInitialized这两个方法publicclass ContextLoaderListener implements ServletContextListener{       privateContextLoader contextLoader;       /**       *Initialize the root web application context.       */      //Spring框架由此启动, contextInitialized也就是监听器类的main入口函数       publicvoid contextInitialized(ServletContextEvent event) {             this.contextLoader = createContextLoader();             this.contextLoader.initWebApplicationContext(event.getServletContext());       }       /**       * Createthe ContextLoader to use. Can be overridden in subclasses.       * @returnthe new ContextLoader      */                                                  protectedContextLoader createContextLoader() {             return new ContextLoader();       }       /**       * Returnthe ContextLoader used by this listener.       * @returnthe current ContextLoader       */       publicContextLoader getContextLoader() {             return this.contextLoader;       }       /**       * Closethe root web application context.       */       publicvoid contextDestroyed(ServletContextEvent event) {             if (this.contextLoader != null) {                    this.contextLoader.closeWebApplicationContext(event.getServletContext());             }       }}

  总的来说这个入口非常简单,所有实现都隐藏在ContextLoader类里。
  ServletContextListener 是ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。
  在JSP文件中,application 是 ServletContext 的实例,由JSP容器默认创建。Servlet 中调用 getServletContext()方法得到 ServletContext 的实例。
  我们使用缓存的思路大概是:
  1. 服务器启动时,ServletContextListener 的contextInitialized()方法被调用,所以在里面创建好缓存。可以从文件中或者从数据库中读取取缓存内容生成类,用 ServletContext.setAttribute()方法将缓存类保存在ServletContext 的实例中。
  2. 程序使用 ServletContext.getAttribute()读取缓存。如果是 JSP,使用application.getAttribute()。如果是 Servlet,使用 getServletContext().getAttribute()。如果缓存发生变化(如访问计数),你可以同时更改缓存和文件/数据库。或者你等 变化积累到一定程序再保存,也可以在下一步保存。
  3. 服务器将要关闭时,ServletContextListener 的 contextDestroyed()方法被调用,所以在里面保存缓存的更改。将更改后的缓存保存回文件或者数据库,更新原来的内容。

  ServletContext 被Servlet 程序用来与 Web 容器通信。例如写日志,转发请求。每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。因为Context可以用来保存资源并且共享,所以我所知道的 ServletContext 的最大应用是Web缓存----把不经常更改的内容读入内存,所以服务器响应请求的时候就不需要进行慢速的磁盘I/O了。


1 0