How to load multiple Spring configuaration files

In this post , we will see how to load multiple spring bean configuration files. Sometimes, you have multiple spring bean configuration file , you may have different configuration file for service, different for business object.
When you are working on complex application, it is not good practice to have only single xml configuration, you can split it into multiple file for better maintenance.
There are two ways to do it.
  • Using application context constructor
  • Using import in xml bean

Using application context constructor:

You can simply create a String array with name of multiple configuration file and pass it application context constructor.
For example:
You can load multiple files using below code:
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"spring-service.xml",
              "spring-businessObjects.xml"});

Using import: 

You can do it using import tag too.
Lets say you have spring-service.xml as below:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="fetchDataService"
class="org.arpit.java2blog.FetchDataService">
 </bean>
</beans>
You have another spring configuration called spring-businessObjects.xml as below:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="businessObject"
class="org.arpit.java2blog.BusinessObject">
 </bean>

</beans>
You can simply import above two files in another xml file called applicationcontext.xml. You need to load applicationcontext.xml to load all bean objects.
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <import resource="spring-service.xml" />
    <import resource="spring-businessObjects.xml " />
 </bean>

</beans>

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012