如何在spring中引用另一个xml文件的bean

我有一个XML文件中定义的Spring bean。 我想从另一个XML文件引用它。 我该怎么办?

你有几个select:

import

<import resource="classpath:config/spring/that-other-xml-conf.xml"/> <bean id="yourCoolBean" class="org.jdong.MyCoolBean"> <property name="anotherBean" ref="thatOtherBean"/> </bean> 

包含在ApplicationContext构造中

当你创build它时,使这两个文件成为你的ApplicationContext的一部分=>然后不需要导入。

例如,如果您在testing期间需要它,

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:META-INF/conf/spring/this-xml-conf.xml", "classpath:META-INF/conf/spring/that-other-xml-conf.xml" }) public class CleverMoneyMakingBusinessServiceIntegrationTest {...} 

万一它是一个Web应用程序,你可以在web.xml做到这一点:

 <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/conf/spring/this-xml-conf.xml</param-value> <param-value>WEB-INF/conf/spring/that-other-xml-conf.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 

如果它是一个独立的应用程序,库等。你会加载你的ApplicationContext为:

 new ClassPathXmlApplicationContext( new String[] { "classpath:META-INF/conf/spring/this-xml-conf.xml", "classpath:META-INF/conf/spring/that-other-xml-conf.xml" } ); 

只需用<import resource="otherXml.xml">定义bean的xml,你就可以使用bean定义。

你可以在resource属性中使用classpath:

 <import resource="classpath:anotherXXML.xml" /> 

请参阅Spring Reference的本章中的“3.18。从一个文件导入Bean定义到另一个文件”

您可以像引用同一个XML文件中的bean一样引用它。 如果一个spring上下文由多个XML文件组成,那么所有的bean都是同一个上下文的一部分,因此共享一个唯一的名称空间。

或者,如果您只是将bean重构为多个文件以防止单个xml文件变大,只需从当前文件夹引用该文件即可:

 <import resource="processors/processor-beans.xml"/> 

您也可以通过在代码中加载多个Spring beanconfiguration文件来解决这个问题:

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

将所有spring xml文件放在项目classpath下:

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

但是,上面的实现是缺乏组织和容易出错的,更好的方法是把你所有的Spring beanconfiguration文件组织成一个XML文件。 例如,创build一个Spring-All-Module.xml文件,并像下面这样导入整个Spring bean文件:

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

现在你可以像这样加载一个XML文件:

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

注意在Spring3中,替代解决scheme是使用JavaConfig @Import 。