ContextLoaderListener作用详解

Spring 中监听器 作用 - ContextLoaderListener:

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

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法

在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成

Spring在web下的入口在配置文件web.xml的监听器中:

  1. <listener>  
  2.         <listener-class>  
  3.           org.springframework.web.context.ContextLoaderListener  
  4.         </listener-class>  
  5. </listener>  
  6. <context-param>  
  7.     <param-name>contextConfigLocation</param-name>  
  8.      <param-value>classpath:conf/spring/applicationContext.xml</param-value>  
  9. </context-param>
上述是在web.xml中的配置信息。

//实现了接口ServletContextListener,也就是说他必须实现contextDestroyed, contextInitialized这两个方法

  1. publicclass ContextLoaderListener implements ServletContextListener{  
  2.        privateContextLoader contextLoader;  
  3.        /** 
  4.        *Initialize the root web application context. 
  5.        */  
  6. //Spring框架由此启动, contextInitialized也就是监听器类的main入口函数  
  7.        publicvoid contextInitialized(ServletContextEvent event) {  
  8.              this.contextLoader = createContextLoader();  
  9.              this.contextLoader.initWebApplicationContext(event.getServletContext());  
  10.        }  
  11.        /** 
  12.        * Createthe ContextLoader to use. Can be overridden in subclasses. 
  13.        * @returnthe new ContextLoader 
  14.       */                                             
  15.        protectedContextLoader createContextLoader() {  
  16.              return new ContextLoader();  
  17.        }  
  18.        /** 
  19.        * Returnthe ContextLoader used by this listener. 
  20.        * @returnthe current ContextLoader 
  21.        */  
  22.        publicContextLoader getContextLoader() {  
  23.              return this.contextLoader;  
  24.        }  
  25.        /** 
  26.        * Closethe root web application context. 
  27.        */  
  28.        publicvoid contextDestroyed(ServletContextEvent event) {  
  29.              if (this.contextLoader != null) {  
  30.                     this.contextLoader.closeWebApplicationContext(event.getServletContext());  
  31.              }  
  32.        }  
  33. }

总的来说这个入口非常简单,所有实现都隐藏在ContextLoader类里.

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

ServletContextListener 是ServletContext 的监听者如果 ServletContext 发生变化,ServletContextListener 就可以监听到,如服务器启动时 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()方法被调用,所以在里面保存缓存的更改。将更改后的缓存保存回文件或者数据库,更新原来的内容。

Java代码:

  1. import User; //my own     
  2. classimport DatabaseManager; // my own class    
  3. import javax.servlet.ServletContext;    
  4. import javax.servlet.ServletContextListener;    
  5. public class MyContextListener  implements ServletContextListener {        
  6.       private ServletContext context = null;        
  7.       public void contextInitialized(ServletContextEvent event) {       
  8.                 context = event.getServletContext();            
  9.                 User user = DatabaseManager.getUserById(1);         
  10.                 context.setAttribute("user1", user);        
  11.       }     
  12.       public void contextDestroyed(ServletContextEvent event) {     
  13.                  User user = (User)context.getAttribute("user1");           
  14.                  DatabaseManager.updateUserData(user);          
  15.                  this.context = null;       
  16.       }    
  17. }

布署 ServletContextListener

      你实现(implements)了 ServletContextListener 编译后,把它放在正确的WEB-INF/classes目录下,更改WEB-INF目录下的 web.xml文件,在web-app节点里添加

<listener>

        <listener-class>MyServletContextListener</listener-class>

</listener>


----------------------------------------在不同的情况下获取数据-----------------------------------------

spring  task定时器类中:

实现ApplicationContextAware接口
 public class A implements ServletContextAware {
           private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void b() {
	servletContext.getAttribute("uid")
     }
}
controller 类中:
  1. ServletContext servletContext=request.getSession().getServletContext();  
  2. ervletContext.getAttribute("uid");  

java普通类中:

   只能从controller 传 servletContext或者仿照task类的方式

ContextLoaderListener初始化

转载自:http://my.oschina.net/pkpk1234/blog/61971

Web容器调用contextInitialized方法初始化ContextLoaderListener,
在此方法中,ContextLoaderListener通过调用继承自 ContextLoader的initWebApplicationContext方法实例化Spring Ioc容器

initWebApplicationContext方法进行的操作如图1:


以上在实例化Spring IoC容器的过程中,最主要的两个方法是
createWebApplicationContext
configureAndRefreshWebApplicationContext方法。

createWebApplicationContext方法用于返回XmlWebApplicationContext实例,即Web环境下的Spring IoC容器

configureAndRefreshWebApplicationContext用于配置XmlWebApplicationContext,读取web.xml中通过contextConfigLocation标签指定的XML文件,实例化XML文件中配置的bean,并在上一步中实例化的容器中进行注册

完成以上两步的操作后Spring MVC会将XmlWebApplicationContext实例以属性的方式注册到ServletContext中
属性的名称由WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE指定,默认值为:WebApplicationContext.class.getName() + ".ROOT"。
此Spring 容器是ROOT上下文,供所有的Spring MVC Servlcet使用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值