Web加载Spring的过程

来源:互联网 发布:php 大数据处理高并发 编辑:程序博客网 时间:2024/05/16 02:50

WebSpringXMLServletlog4j 

在WEB应用中集成Spring的非常简单:只需要在web.xml中配置
<listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
那么,Spring容器会自动启动,那么Spring是怎样一步步加载到web容器中呢?
    众所周知,web容器会自动加载web.xml中的listener、filter、servlet。所有Listener都实现了J2EE规范的接口:ServletContextListener,实现接口中两个方法:

  public abstract void contextInitialized(javax.servlet.ServletContextEvent arg0);
  public abstract void contextDestroyed(javax.servlet.ServletContextEvent arg0);

    当Web容器启动的时候,容器会自动实例化Spring的监听实现类ContextLoaderListener,并调用contextInitialized接口。当web容器退出的时候,web容器会自动调用contextDestroyed接口,销毁监听器对象。那么,Spring的监听器类ContextLoaderListener在初始化的时候是怎样一步步加载的?
    分析代码,我们看到

    public void contextInitialized(ServletContextEvent event) {
        this.contextLoader = createContextLoader();
        this.contextLoader.initWebApplicationContext(event.getServletContext());
    }

 

createContextLoader函数只做了一件事情:

    protected ContextLoader createContextLoader() {
        return new ContextLoader();
    }

真正的初始化过程是调用ContextLoader类的initWebApplicationContext方法,即初始化Spring的WebApplicationContext容器。ContextLoader.initWebApplicationContext(ServletContext servletContext)需要一个ServletContext对象,就是web容器的上下文对象servletContext,在web容器中它只有一份。对象中包含了web.xml配置的初始化参数,例如,我们可以杂web.xml中配置如下内容,告诉Spring容器要加载的xml文件的位置。

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>

那么在程序中,只要可以获取到ServletContext对象的实例,就可以通过servletContext.getAttribute(param-name)轻松地获取到param-value的值。

    进入initWebApplicationContext函数后,Spring首先从ServletContext中获取一个key为org.springframework.web.context.WebApplicationContext.ROOT的值,如果不为空,说明在ServletContext中已经存在一份根application,则抛出异常。首先