---
title: "ApplicationContext的三种实现方式以及在web.xml配置的两种方式 "
author: "onlyor"
date: "2014-12-19T09:42:04Z"
tags: []
categories: ["企业架构"]
slug: "applicationcontext-web-xml"
draft: false
lastmod: "2014-12-19T09:42:04Z"
id: 2168546
url: "https://onlyor.iteye.com/blog/2168546"
---

ApplicationContext 是 BeanFactory 接口的子接口，它增强了 BeanFactory 的功能，处于 context 包下。很多时候， ApplicationContext 允许以声明式方式操作容器，无须手动创建。可利用如 ContextLoader 的支持类，在 Web 应用启动时自动创建 ApplicationContext。当然，也可以采用编程方式创建ApplicationContext。

ApplicationContext包括BeanFactory的全部功能，因此建议优先使用ApplicationContext。除非对于某些内存非常关键的应用，才考虑使用 BeanFactory。

 

spring为ApplicationContext提供的3种实现分别为：

1、  **ClassPathXmlApplicationContext**：利用类路径的XML文件来载入Bean定义的信息

\[1]  ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");

\[2]  String\[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};

ApplicationContext ctx = new ClassPathXmlApplication(locations);

2、 **FileSystemXmlApplicationContext**：利用文件系统中的XMl文件来载入Bean

定义的信息

\[1]  ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加载单个配置文件

\[2]  String\[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};

 ApplicationContext ctx = new FileSystemXmlApplicationContext(locations );

//加载多个配置文件

\[3]  ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");

//根据具体路径加载

3、 **XmlWebApplicationContext**：从Web系统中的XML文件来载入Bean定义的信息。

 ServletContext servletContext = request.getSession().getServletContext();    

 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

 

 

配置WebApplicationContext的两种方法：

（1）        利用**Listener**接口来实现

&lt;listener&gt;

       &lt;listener-class&gt;

org.springframework.web.context.ContextLoaderListener

&lt;/listener-class&gt;

&lt;/listener&gt;

&lt;context-param&gt;

       &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;

       &lt;param-value&gt;classpath:applicationContext&lt;/param-value&gt;

&lt;/context-param&gt;

（2）        利用**Servlet**接口来实现

&lt;context-param&gt;

&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;

&lt;param-value&gt;classpath:applicationContext&lt;/param-value&gt;

&lt;/context-param&gt;

&lt;Servlet&gt;

       &lt;servlet-name&gt;context&lt;/servlet-name&gt;

       &lt;servlet-class&gt;

           org.springframework.web.context.ContextLoaderServlet

       &lt;/servlet-class&gt;

&lt;/servlet&gt;