---
title: "spring多文件的几种配置方法"
author: "cfeers"
date: "2010-08-26T15:49:35Z"
tags: ["Bean", "Servlet", "Spring", "Web", "XML"]
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-08-26T15:49:35Z"
id: 747911
url: "https://cfeers.iteye.com/blog/747911"
---

spring多配置文件在web.xml中的几种配置方式：  
往往在实际的开发当中会涉及到许多的spring配置文件。那么这些配置文件应该如何在web.xml中配置呢？  
&lt;1&gt;：  
&lt;context-param&gt;  
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
  &lt;param-value&gt;/WEB-INF/classes/applicationContext-\*.xml,classpath\*:application-\*.xml&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;

&lt;2&gt;:  
&lt;context-param&gt;  
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
  &lt;param-value&gt;  
    /WEB-INF/classes/applicationContext.xml  
/WEB-INF/classes/applicationContext2.xml  
  &lt;/param-value&gt;  
&lt;/context-param&gt;  
&lt;3&gt;：  
&lt;beans&gt;  
  &lt;bean id="default" class="org.springframework.context.support.ClassPathXmlApplicationContext"&gt;  
    &lt;constructor-arg&gt;  
      &lt;list&gt;  
        &lt;value&gt;applicationContext.xml&lt;/value&gt;  
        &lt;value&gt;applicationContext-business.xml&lt;/value&gt;  
        &lt;value&gt;applicationContext-scheduler.xml&lt;/value&gt;  
      &lt;/list&gt;  
    &lt;/constructor-arg&gt;  
  &lt;/bean&gt;  
&lt;/beans&gt;

然后在web.xml文件中,使用自己定义的ContextLoaderServlet来启动,这个ContextLoaderServlet可以继承HttpServlet,  
在它inti()时候取得BeanFactory,代码如下：  
public class ContextLoaderServlet extends HttpServlet {  
  public ContextLoaderServlet() {}  
  public init()  throws ServletException{  
     //这个参数里的名字就是我们在BeanRefFactory.xml里定义的bean的名字。  
DefaultBeanFactory.getFactory("default");  
  }  
  public destory() {}  
}

然后定义一个DefaultBeanFactory类  
public class DefaultBeanFactory () {  
  proterced static final BeanFactory getFactory (String s) {  
  BeanFactoryLocator beanfactorylocator = SingletonBeanFactoryLocator.getInstance();  
  BeanFactoryReference beanfactoryreference = beanfactorylocator.useBeanFactory(s);  
  return beanfactoryreference.getFactory();    
  }  
}

最后在web.xml中的配置  
最后在web.xml文件中配置如下：  
&lt;servlet&gt;  
  &lt;servlet-name&gt;context&lt;/servlet-name&gt;  
  &lt;servlet-class&gt;com.tks.web.servlet.ContextLoaderServlet&lt;/servlet-class&gt;  
  &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;  
&lt;/servlet&gt;

**在一个主spring配置文件中，import其它spring配置文件就行了**