tomcat服务器启动入口文件是web.xml,通过在其中配置相关的Listener和servlet即可加载Spring MVC所需数据。基于Spring MVC最简单的配置如下。
<!-- 加载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加载到容器里面。
DispatcherServlet是一个请求分发器,所有匹配的URL都会都会通过该Servlet分发执行,在创建Servlet对象时会初始化Spring MVC相关配置。
在web.xml中,我们看到基于ContextLoaderListener和DispatcherServlet都可以配置spring相关的xml,但是两种方式加载spring的ApplicationContext上下文对象并不是合并存储的。所以建议,基于mvc相关的spring配置由DispatcherServlet加载,而其他的JavaBean则由ContextLoaderListener加载。
一.ContextLoaderListener
ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的创建),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操作)。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
ContextLoaderListener加载Spring上下文的过程可以用以下图表示,黄色区域是核心代码区。
简单介绍一下上图的运行流程:
1.启动项目时触发contextInitialized方法,该方法就做一件事:通过父类ContextLoad的initWebApplicationContext方法创建Spring上下文对象。
2.initWebApplicationContext方法做了三件事情,创建WebApplicationContext;加载对应spring配置文件里创建的bean实例,将WebApplicationContext方法放入ServletContext中(java Web的全局变量)中。
3.createWebApplicationContext创建上下文对象,支持用户自定义上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用XmlWebApplicationContext作为ApplicationContext(它仅仅是一个接口)的实现。
4. configureAndRefreshWebApplicationContext方法用于封装ApplicationContext数据并且初始化所有相关Bean对象,它会从web.xml中读取取名为contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用refresh方法执行所有java对象的创建。
5.完成ApplicationContext创建后就是将其放入ServletContext中,注意它存储的key值常量。