Spring Tutorial - Spring Multiple Configuration File








In a large project, we may have more than one Spring's bean configuration files. Put every single bean definition in a single file is hard to maintain. And they may be stored in different folder structures.

For example, we may have a Spring-Common.xml in common folder, a Spring-Connection.xml in connection folder, and a Spring-ModuleA.xml in ModuleA folder.

Load one by one

One way to load the configuration files is to load them one by one.

For example, we put all above three xml files in classpath

project-classpath/Spring-Common.xml
project-classpath/Spring-Connection.xml
project-classpath/Spring-ModuleA.xml

Then we can use the following code to load multiple Spring bean configuration files.

ApplicationContext context = 
    new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml",
              "Spring-Connection.xml","Spring-ModuleA.xml"});

The code above pass in all file names one by one to the ClassPathXmlApplicationContext. The problem is that we have to change the code if we need to add new file name.





import xml file

Spring allows us to organize all Spring bean configuration files into a single XML file.

In order to host all configuration file we created a new Spring-All-Module.xml file, and import the other Spring bean files.

<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-2.5.xsd">
  <import resource="common/Spring-Common.xml"/>
    <import resource="connection/Spring-Connection.xml"/>
    <import resource="moduleA/Spring-ModuleA.xml"/>
</beans>

Put this file under project classpath.

project-classpath/Spring-All-Module.xml

We can load a single xml file like this :

ApplicationContext context = 
    new ClassPathXmlApplicationContext("Spring-All-Module.xml");