Spring框架学习[Web环境中Spring的启动过程](一)

2014-11-24 03:05:48 · 作者: · 浏览: 7

1.Spring不但可以在JavaSE环境中应用,在Web环境中也可以广泛应用,Spring在web环境中应用时,需要在应用的web.xml文件中添加如下的配置:

[xhtml] view plaincopyprint …… contextConfigLocation /WEB-INF/applicationContext.xml org.springframework.web.context.ContextLoaderListener ……

通过web描述文件我们可以看到,Spring在Web环境中通过ContextLoaderListener监听器类启动,通过加载”/WEB-INF/”目录下的Spring配置文件,Web服务器启动Spring的初始化过程。

ContextLoaderListener是一个监听器,和Web服务器的生命周期事件紧密关联,即当Web服务器启动时,Web服务器声明周期事件将会触发ContextLoaderListener监听器加载Spring配置文件,开始Spring在web服务器中的初始化工作。

2.ContextLoaderListener启动Spring:

ContextLoaderListener继承Spring的ContextLoader上下文加载器类,同时实现ServletContextListener接口(Servlet上下文监听器),监听Web服务器上下文的启动和停止事件,管理Web环境中Spring的启动和销毁过程,其源码如下:

[java] view plaincopyprint public class ContextLoaderListener extends ContextLoader implements ServletContextListener { //Spring上下文加载器 private ContextLoader contextLoader; //初始化Spring根上下文,event参数是当前Web应用上下文事件 public void contextInitialized(ServletContextEvent event) { //创建Spring上下文加载器,ContextLoaderListener继承ContextLoader, //所以ContextLoaderListener本身也是Spring的上下文加载器 this.contextLoader = createContextLoader(); if (this.contextLoader == null) { this.contextLoader = this; } //根据给定的ServletContext上下文,初始化Spring Web应用上下文 this.contextLoader.initWebApplicationContext(event.getServletContext()); } //创建Spring上下文加载器 protected ContextLoader createContextLoader() { return null; } //获取Spring上下文加载器 public ContextLoader getContextLoader() { return this.contextLoader; } //销毁Spring根上下文 public void contextDestroyed(ServletContextEvent event) { if (this.contextLoader != null) { //关闭指定Servlet的Spring Web根上下文 this.contextLoader.closeWebApplicationContext(event.getServletContext()); } //清除Servlet上下文中被配置的属性 ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }

通过对ContextLoaderListener的源码分析,我们看到ContextLoaderListener继承ContextLoader,所以ContextLoaderListener本身也是Spring的上下文加载器。

ContextLoaderListener实现了ServletContextListener接口,当Web应用在Web服务器中被被启动和停止时,Web服务器启动和停止事件会分别触发Conte