spring加载过程

tomcat服务器启动入口文件是web.xml,经过在其中配置相关的Listener和servlet便可加载Spring MVC所需数据。基于Spring MVC最简单的配置以下。java

<!-- 加载Spring配置文件 -->  
<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
    classpath:spring-context*.xml  
    </param-value>  
</context-param>  
<listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>  
  
<!-- 加载spring mvc -->  
<servlet>  
    <servlet-name>spring3mvc</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
        classpath:spring-mvc*.xml  
        </param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>  
  
<servlet-mapping>  
    <servlet-name>spring3mvc</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>

ContextLoaderListener基于Web上下文级别的监听器在启动服务器时就建立ApplicationContext而且将配置的Spring Bean加载到容器里面。web

DispatcherServlet是一个请求分发器,全部匹配的URL都会都会经过该Servlet分发执行,在建立Servlet对象时会初始化Spring MVC相关配置。spring

在web.xml中,咱们看到基于ContextLoaderListener和DispatcherServlet均可以配置spring相关的xml,可是两种方式加载spring的ApplicationContext上下文对象并非合并存储的。因此建议,基于mvc相关的spring配置由DispatcherServlet加载,而其余的JavaBean则由ContextLoaderListener加载。spring-mvc

一.ContextLoaderListenertomcat

    ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的建立),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操做)。服务器

public class ContextLoaderListener extends ContextLoader implements ServletContextListener

ContextLoaderListener加载Spring上下文的过程能够用如下图表示,黄色区域是核心代码区。mvc

简单介绍一下上图的运行流程:app

1.启动项目时触发contextInitialized方法,该方法就作一件事:经过父类ContextLoad的initWebApplicationContext方法建立Spring上下文对象。url

2.initWebApplicationContext方法作了三件事情,建立WebApplicationContext;加载对应spring配置文件里建立的bean实例,将WebApplicationContext方法放入ServletContext中(java Web的全局变量)中。spa

3.createWebApplicationContext建立上下文对象,支持用户自定义上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用XmlWebApplicationContext做为ApplicationContext(它仅仅是一个接口)的实现。

4.  configureAndRefreshWebApplicationContext方法用于封装ApplicationContext数据而且初始化全部相关Bean对象,它会从web.xml中读取取名为contextConfigLocation的配置,这就是spring xml数据源设置,而后放到ApplicationContext中,最后调用refresh方法执行全部java对象的建立。

5.完成ApplicationContext建立后就是将其放入ServletContext中,注意它存储的key值常量。

相关文章
相关标签/搜索