Spring拥有多个xml配置文件的情况

1:在加载Spring容器时,加载多个xml配置文件。

   <context-param>

        <param-name>contextConfigLocation</param-name>

       <param-value>/WEB-INF/applicationContext.xml , /WEB-INF/applicationContext2.xml</param-value>

    </context-param>

或者

ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"conf/bean1.xml","conf/bean2.xml"});

2:在加载Spring容器时,加载单个xml配置文件,但要通过import 方式整合其他xml配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:applicationContext1.xml" />
    <import resource="classpath:applicationContext2.xml" />

</beans>


原理总结:

1、配置文件会先合并,后解析,也就是说,无论是命名空间还是配置的内容,都会合并处理。

2、因为多个 Spring 配置文件最终会合并到一起(形成一个 ApplicationContext),因此这些配置中的 bean 都是可以互相引用的。
 

原文地址:https://www.cnblogs.com/hzcya1995/p/13302460.html