---
title: "spring在web.xml的配置"
author: "GameWong"
date: "2013-04-09T14:19:31Z"
tags: []
categories: ["Web前端"]
slug: "spring-web-xml"
draft: false
lastmod: "2013-04-09T14:19:31Z"
id: 1844440
url: "https://gamewong.iteye.com/blog/1844440"
---

### **spring在web.xml中的配置**

在实际项目中spring的 配置文件applicationcontext.xml是通过spring提供的加载机制，自动加载的容器中去，在web项目中，配置文件加载到web容 器中进行解析，目前，spring提供了两种加载器，以供web容器的加载：一种是ContextLoaderListener，另一种是 ContextLoaderServlet。这两种在功能上完全相同，只是一种是基于Servlet2.3版本中新引入的Listener接口实现，而另 一种是基于Servlet接口实现，以下是这两种加载器在web.xml中的时机配置应用：

第一种：

&lt;listener&gt;  
 &lt;listener-class&gt;org.springframework.context.ContextLoaderListener&lt;/listener-class&gt;  
&lt;/listener&gt;

另一种：

&lt;servlet&gt;  
 &lt;servlet-name&gt;context&lt;/servlet-name&gt;  
 &lt;servlet-class&gt;org.springframework.context.ContextLoaderServlet&lt;/servlet-class&gt;  
 &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;  
&lt;/servlet&gt;

通过上面的配置，web容器会自动加载applicationcontext.xml初始化。

如果需要指定配置文件的位置，可通过context-param加以指定：

&lt;context-param&gt;  
 &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
 &lt;param-value&gt;/WEB-INF/myApplicationContext.xml&lt;/param-value&gt;  
&lt;/context-param&gt;

之后，可以通过

WebApplicationContextUtils.getWebApplicationContext方法在web应用中获取applicationcontext的引用。