Main Tutorials

How to load multiple Spring bean configuration file

Problem

In a large project structure, the Spring’s bean configuration files are located in different folders for easy maintainability and modular. For example, Spring-Common.xml in common folder, Spring-Connection.xml in connection folder, Spring-ModuleA.xml in ModuleA folder…and etc.

You may load multiple Spring bean configuration files in the code :


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

Put all spring xml files under project classpath.


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

Solution

The above ways are lack of organizing and error prone, the better way should be organized all your Spring bean configuration files into a single XML file. For example, create a Spring-All-Module.xml file, and import the entire Spring bean files like this :

File : Spring-All-Module.xml

<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>

Now you can load a single xml file like this :


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

Put this file under project classpath.


	project-classpath/Spring-All-Module.xml
Note
In Spring3, the alternative solution is using JavaConfig @Import.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
chitta
8 years ago

if suppose there are two spring config file one is for service and one is for DAO if I want to get a ref of service bean in to dao bean so how can i refer in spring xml file?

shareef
8 years ago

please check mkyong work on my github account

https://github.com/shareefhiasat/mkyong

baba
8 years ago

What is the result in case that resources are imported into an applicationContext.xml file? Do I get a one large applicationConext file, I mean all the imported stuff, and the stuff in the importing file act like they were all in the same file?
Or each file has its own context?
An example that I can think of is when a bean is configured as singleton in one of the files – is it going to be the same instance across all the imported and importing files?

Mayank
8 years ago

Can u send ? all three spring xml file so that everything clear because still confuse in module spring xml fille.

abhishek
9 years ago

good

Ashis pandey
10 years ago

Thanks Really very clear cut example.for how we configure multiple configuration

Thanks Keep it Up!!!!

van helsing
10 years ago

this is bean.xml file. whenever i change property name like if i give name of property is “song” then it will show exceptions why?????

saran
10 years ago

i have seen above type of usage, what does it mean?

cherry
10 years ago

i have seen above type of usage, what does it mean?

Narasim
11 years ago

Its really helped me in fixing multiple outgoing emails generation in quartz spring email schedule . It suppose to generate single mail on loading the applicationcontext.xml to generate emails. I created new configuration.xml as mentioned in this blog fixed my issue.

Your blog is Very useful, togo and informative to many people. Thanks and please keep it up.

Steve
11 years ago

He left out the quotes when creating the ApplicationContext, it should be:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-All-Module.xml");
Jay
11 years ago

I really do enjoy your blogs. Very useful and informative. Please keep it up.

Kumar Saurabh
11 years ago

Please let me know what should be the scenario in case, common/Spring-Common.xml is already loaded by some ClassPathXmlApplicationContext before it is again loaded through Spring-All-Module.xml.

In my case, it is failing with org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to register bean definition with name ‘packageAdmin’

Offending resource: URL [jar:file:/home/pg/partygaming/lib/inhouse/pg-serviceregistry-non_osgi-extra.jar!/META-INF/spring/serviceregistry-nonosgi-be

an-context.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name ‘packageAdmin

‘ defined in URL [jar:file:/home/pg/partygaming/lib/inhouse/pg-serviceregistry-non_osgi-extra.jar!/META-INF/spring/serviceregistry-nonosgi-bean-cont

ext.xml]: Cannot register bean definition [Generic bean: class [com.partygaming.serviceregistry.packageadmin.PackageAdminImpl]; scope=; abstract=fal

se; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMeth

odName=null; destroyMethodName=null; defined in URL [jar:file:/home/pg/partygaming/lib/inhouse/pg-serviceregistry-non_osgi-extra.jar!/META-INF/sprin

g/serviceregistry-nonosgi-bean-context.xml]] for bean ‘packageAdmin’: There is already [Generic bean: class [com.partygaming.serviceregistry.package

admin.PackageAdminImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBe

anName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [META-INF/spring/serviceregistry-no

nosgi-bean-context.xml]] bound.

at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)

at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)

at org.springframework.context.support.AbstractRefreshableConfigApplicationContext.afterPropertiesSet(AbstractRefreshableConfigApplicationCo

ntext.java:150)

at com.pg.framework.bootstrap.PGBootstrap.initialize(PGBootstrap.java:87)

at com.pg.framework.bootstrap.PGBootstrap.main(PGBootstrap.java:70)

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name ‘packageAdmin’ defined in URL [jar:file

:/home/pg/partygaming/lib/inhouse/pg-serviceregistry-non_osgi-extra.jar!/META-INF/spring/serviceregistry-nonosgi-bean-context.xml]: Cannot register

bean definition [Generic bean: class [com.partygaming.serviceregistry.packageadmin.PackageAdminImpl]; scope=; abstract=false; lazyInit=false; autowi

reMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethod

Name=null; defined in URL [jar:file:/home/pg/partygaming/lib/inhouse/pg-serviceregistry-non_osgi-extra.jar!/META-INF/spring/serviceregistryRe-nonosgi-

Asraf
11 years ago

Simple and clear

Srilatha
11 years ago

Simple and clear examples..thanks

paul
11 years ago

You dont mention where these directories should exist. Are they inside WEB-INF/classes??

Anurag @ cisco
12 years ago

What an Example !! excellent ….. truelly awesome

papas
10 years ago
Reply to  Anurag @ cisco

It helps a Lot to learn.

reddynr
7 years ago

Hi,

I have a requirement to load applicationContext-local.xml dynamically [based on parameter]. here is the sample

applicationContext_local_IND.xml
applicationContext_local_MX.xml

any advice. Thank you