Saturday, July 28, 2012

How to load multiple Spring bean configuration file

When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex. Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

You may load multiple Spring bean configuration files in code :
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",
              "Spring-Common.xml"});

This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML into ClassPathXmlApplicationContext
Ex. 
<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-Core.xml"/>  
      <import resource="connection/Spring-Common.xml"/> 
</beans>
Load Spring-Main.xml as
ApplicationContext context = new ClassPathXmlApplicationContext(Spring-Main.xml);
Or put xml under project classpath.  project-classpath/Spring-Main.xml
 

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/