---
title: "spring"
author: "salouhim"
date: "2011-07-19T15:18:38Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: true
lastmod: "2011-07-19T15:18:38Z"
id: 1128008
url: "https://salouhim.iteye.com/blog/1128008"
---

加载器目前有两种选择：ContextLoaderListener和ContextLoaderServlet。   
         这两者在功能上完全等同，只是一个是基于Servlet2.3版本中新引入的Listener接口实现，而另一个基于Servlet接口实现。开发中可根据目标Web容器的实际情况进行选择。 

配置非常简单，在web.xml中增加：   
&lt;listener&gt;   
       &lt;listener-class&gt;   
          org.springframework.web.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.web.context.ContextLoaderServlet   
         &lt;/servlet-class&gt;   
         &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;   
&lt;/servlet&gt;  

通过以上配置，Web容器会自动加载/WEB-INF/applicationContext.xml初始化   
ApplicationContext实例，如果需要指定配置文件位置，可通过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引用。 

如：ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext();   
         LoginAction action=(LoginAction)ctx.getBean("action");

 

如：我在jsp界面中用到：

    

      WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);     
   DataSource ds = (DataSource) context.getBean("dataSource");

   Connection   con = ds.getConnection();