spring实现的大型项目中,如何实现整合多个配置文件?

对于大型项目来说,为了防止开发时配置文件的资源竞争(多人同时修改一个配置文件不方便),或为了使模块资源便于拆卸,往往每个模块都拥有自己独立的配置文件。

例如,项目中有如下三个配置文件:

1. spring-dao.xml

2. spring-service.xml

3. spring-controller.xml

那么我们怎么整合这些配置文件呢?

方法一:你可以在代码中加载以上3个xml配置文件

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {" spring-dao.xml","spring-service.xml","spring-controller.xml"});

  

但是这种方法不易组织并且不好维护。

  

方法二:我们通过<import>将多个配置文件引入到一个文件中,进行配置文件的集成,这样启动spring容器时,仅需要指定这个合并好的配置文件就可以。 

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-controller.xml"/>
</beans>

  

推荐使用此种方法。

<import>元素具体说明:

<import>元素中的resource属性支持spring的标准路径资源:

1、classpath: 从类路径下加载资源,classpath: 和classpath:/等同

     示例:classpath:spring-dao.xml

2、file: 从文件系统目录中装载资源,可采用绝对和相对的路径

     示例:file:/conf/spring-dao.xml

3、http:// 从web服务器中加载资源

     示例:http://www.yanln.com/resource/spring-dao.xml

4、ftp://  从ftp服务器中加载资源

     示例:ftp://www.yanln.com/resource/spring-dao.xml

猜你喜欢

转载自yanln.iteye.com/blog/2211072