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

Jef*_*ong 36 java spring reference javabeans

我在xml文件中定义了一个Spring bean.我想从另一个xml文件中引用它.我该怎么办呢?

tol*_*ius 54

你有几个选择:

进口

<import resource="classpath:config/spring/that-other-xml-conf.xml"/>

<bean id="yourCoolBean" class="org.jdong.MyCoolBean">
    <property name="anotherBean" ref="thatOtherBean"/>
</bean>
Run Code Online (Sandbox Code Playgroud)


包括在ApplicationContext建筑中

ApplicationContext在创建文件时将这两个文件作为您的一部分=>然后不需要导入.

例如,如果您在测试期间需要它:

@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 {...}
Run Code Online (Sandbox Code Playgroud)

如果它是一个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>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 对我来说,`web.xml`块会抛出错误.一个"param-value"似乎只允许到位. (4认同)

Xav*_*ica 6

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

您可以classpath:resource属性中使用:

<import resource="classpath:anotherXXML.xml" />
Run Code Online (Sandbox Code Playgroud)

请参阅Spring Reference的本章中的"3.18.将Bean定义从一个文件导入另一个文件"


JB *_*zet 5

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