---
title: "Web应用中自动加载 ApplicationContext"
author: "mintelong"
date: "2010-05-13T13:05:09Z"
tags: []
categories: ["Web前端"]
slug: "web-applicationcontext"
draft: false
lastmod: "2010-05-13T13:05:09Z"
id: 665524
url: "https://mintelong.iteye.com/blog/665524"
---

**Web应用中自动加载 ApplicationContext**

对于 Web 应用，不必在代码中手动实例化 ApplicationContext。可通过 ContextLoader声明式地创建 ApplicationContext0ContextLoader有以下两个实现类:

ContextLoaderListener。

ContextLoaderServlet。

这两类功能相同，只是 listener不能在 Servlet2.2 兼容的容器中使用。根据 Servlet2.4规范， listener 会随 Web 应用启动时自动初始化，很多 Serlet 2.3 兼容的容器也提供该功能。

**使用 ContextLoader Listener**

使用 ContextLoaderListener 注册 ApplicationContext 的配置文件如下，注意:下面的配置文件不是在 Spring 的配置文件中增加，而是在 web.xm1文件中增加。

```
 <!确定配置文件的位置--〉
<context-param><param-name>contextConfigLocation</param-name>
<!--此处可以列出多个Spring 的 XML 配置文件→
<param-value>/WEB-INF/daoContext.xml/WEB-iNF/applicationContext.xml</
param-value></context-param>
<!-- 应用启动时，自动加载listener，该 listener会读取上面确定的XML配置文件。
然后创建ApplicationContext实例--〉
<listener>
<listener-class>org.springframework.web.context.ContextLoader
Listener</listener-class>
</listener>
```

**使用 ContextLoaderServlet**

使用 ContextLoaderServlet注册 ApplicationContext的配置文件如下。同样，下面的配置文件也不是在Spring的配置文件中增加，而是在web.xm1文件中增加。

```
 <servlet>
<!--确定Servlet 的名-->
<servlet-name>context</servlet-name><!--确定 Servlet对应的类--〉
<servlet-class>org.springframework.web.context.ContextLoaderServlet</
servlet-class>
<!--确定Servlet的启动级别--〉
<load-on-startup>l</load-on-startup></servlet>
```

采用这种方式时，应将context 的启动级别设成最小，即最优先启动。因为ApplicationContext是整个应用的核心。

注意:在两种启动方式中，推荐采用第一种。因为根据Servlet2.4规范， listener比Servlet优先启动;关键问题是有些容器并不支持Serlet2.4规范，即不支持listener。支持 listener的容器有:

ApacheTomcat4.x 及更高版本。

Jetty4.x及更高版本。

Resin 2.1.8 及更高版本。

Orion2.0.2及更高版本。

BEAWebLogic8.1 SP3

不支持 listener 的容器有:

BEAWebLogicupto 8.1 SP2 及更低版本。

IBMWebSphere 5.x 及更低版本。

OracleOC4J9.0.3 及更低版本。