---
title: "spring学习之ApplicationContext"
author: "zlk"
date: "2010-06-19T09:50:59Z"
tags: ["Servlet", "Spring", "Web", "XML", "编程"]
categories: ["企业架构"]
slug: "spring-applicationcontext"
draft: false
lastmod: "2010-06-19T09:50:59Z"
id: 694384
url: "https://zlk.iteye.com/blog/694384"
---

与BeanFactory通常以编程的方式被创建不同的是，ApplicationContext能以声明的方式创建，如使用ContextLoader。当然你也可以使用ApplicationContext的实现之一来以编程的方式创建ApplicationContext实例。首先，让[我](http://www.gold98.net/)们先分析ContextLoader接口及其实现。

    ContextLoader接口有两个实现：ContextLoaderListener和ContextLoaderServlet。两者都实现同样的功能，但不同的是，ContextLoaderListener不能在与Servlet 2.2兼容的web容器中使用。根据Servlet 2.4规范, servlet context listener要在web应用程序的servlet context建立后立即执行，并要能够响应第一个请求(在servlet context要关闭时也一样)：这样一个servlet context listener是初始化Spring ApplicationContext的理想场所。虽然使用哪个完全取决于你，但是在同等条件下应该首选ContextLoaderListener；对于更多兼容性的信息，请查看ContextLoaderServlet的JavaDoc。

    你可以象下面那样使用ContextLoaderListener来注册一个ApplicationContext：

&lt;context-param&gt;  
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
  &lt;param-value&gt;/WEB-INF/daoContext.[xml](http://www.gold98.net/blog/default.asp?tag=xml) /WEB-INF/applicationContext.[xml](http://www.gold98.net/blog/default.asp?tag=xml)&lt;/param-value&gt;  
&lt;/context-param&gt;

&lt;listener&gt;  
  &lt;listener-class&gt;org.[spring](http://www.gold98.net/blog/default.asp?tag=spring)framework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
&lt;/listener&gt;

&lt;!-- or use the ContextLoaderServlet instead of the above listener  
&lt;servlet&gt;  
  &lt;servlet-name&gt;context&lt;/servlet-name&gt;  
  &lt;servlet-class&gt;org.[spring](http://www.gold98.net/blog/default.asp?tag=spring)framework.web.context.ContextLoaderServlet&lt;/servlet-class&gt;  
  &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;  
&lt;/servlet&gt;  
\--&gt;

    监听器首先检查contextConfigLocation参数，如果它不存在，它将使用/WEB-INF/applicationContext.[xml](http://www.gold98.net/blog/default.asp?tag=xml)作为默认值。如果已存在，它将使用分隔符（逗号、冒号或空格）将字符串分解成应用上下文将位置路径。ContextLoaderServlet同ContextLoaderListener一样使用'contextConfigLocation'参数。