---
title: "使用web.xml方式加载Spring时，获取Spring context的两种方式"
author: "cysunc"
date: "2008-08-02T02:25:52Z"
tags: []
slug: "web-xml-spring-spring-context"
draft: false
lastmod: "2008-08-02T02:25:52Z"
id: 223263
url: "https://chanson.iteye.com/blog/223263"
---

使用web.xml方式加载Spring时，获取Spring context的两种方式：

 

1、servlet方式加载时：

【web.xml】

  &lt;servlet&gt;  
        &lt;servlet-name&gt;dispatcherServlet&lt;/servlet-name&gt;  
        &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;  
        &lt;init-param&gt;  
            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
            &lt;param-value&gt;/WEB-INF/applicationContext&lt;/param-value&gt;  
        &lt;/init-param&gt;  
    &lt;/servlet&gt;

 

【jsp/servlet】

 

ServletContext context = getServletContext();  
    
  XmlWebApplicationContext applicationContext = (XmlWebApplicationContext) context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");

  DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");

 

 

2、listener方式加载时：

【web.xml】

&lt;context-param&gt;  
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
  &lt;param-value&gt;/WEB-INF/applicationContext&lt;/param-value&gt;  
 &lt;/context-param&gt;

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

 

【jsp/servlet】

 

ServletContext context = getServletContext();

     
   WebApplicationContext applicationContext  = WebApplicationContextUtils  
     .getWebApplicationContext(context);  
   

 

  DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");