ServletContext,即Servlet环境对象或Servlet容器,包含从容器环境中获得的初始化信息,其内提供的属性和方法在同一web应用下的所有servelt中被使用。每一个web-app只能有一个ServeltContext,web-app可以是一个放置web application文件的文件夹,也可以是一个.war。

    ApplicationContext 是Spring的核心,Context我们通常解释为上下文环境,我想用“容器”来表述它更容易理解一些,ApplicationContext则是“应 用的容器”了:P,Spring把Bean放在这个容器中,在需要的时候,用getBean方法取出,虽然我没有看过这一部分的源代码,但我想它应该是一 个类似Map的结构。
在Web应用中,我们会用到WebApplicationContext,WebApplicationContext继 承自ApplicationContext,先让我们看看在Web应用中,怎么初始化WebApplicationContext,在web.xml中定 义:

ServletContext与ApplicationContext_Java
<context-param>      
<param-name>contextConfigLocation</param-name>      
<param-value>/WEB-INF/applicationContext.xml</param-value>      
</context-param>      
     
<listener>      
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      
</listener>   
<servlet>      
<servlet-name>context</servlet-name>      
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>      
<load-on-startup>1</load-on-startup>      
</servlet> 
ServletContext与ApplicationContext_Java

 

可以看出,有两种方法,一个是用ContextLoaderListener这个Listerner,另一个是ContextLoaderServlet这 个Servlet,这两个方法都是在web应用启动的时候来初始化WebApplicationContext,我个人认为Listerner要比 Servlet更好一些,因为Listerner监听应用的启动和结束,而Servlet得启动要稍微延迟一些,如果在这时要做一些业务的操作,启动的前 后顺序是有影响的。

    那么在ContextLoaderListener和ContextLoaderServlet中到底做了什么呢?
以ContextLoaderListener为例,我们可以看到
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
protected ContextLoader createContextLoader() {
return new ContextLoader();
}
 
    ContextLoader 是一个工具类,用来初始化WebApplicationContext,其主要方法就是initWebApplicationContext,我们继续追 踪initWebApplicationContext这个方法(具体代码我不贴出,大家可以看Spring中的源码),我们发现,原来 ContextLoader是把WebApplicationContext(XmlWebApplicationContext是默认实现类)放在了 ServletContext中,ServletContext也是一个“容器”,也是一个类似Map的结构,而 WebApplicationContext在ServletContext中的KEY就是 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,我们如果要使用 WebApplicationContext则需要从ServletContext取出,Spring提供了一个 WebApplicationContextUtils类,可以方便的取出WebApplicationContext,只要把 ServletContext传入就可以了。