Spring(4)-How to load multiple Spring bean configuration file

Problem

In a large project structure, the Spring’s bean configuration files are located at 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 code :

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


Or 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 organize and error prone, the better way should be organize all your Spring bean configuration files into a single XML file. For example, create aSpring-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);
	Or put this file under project classpath.
	project-classpath/Spring-All-Module.xml
Note
In Spring3, the alternative solution is using JavaConfig @Import.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值