我在一个xml文件中定义了一个Spring bean。我想从另一个xml文件中引用它。我该怎么做呢?
<import resource="classpath:config/spring/that-other-xml-conf.xml"/>
<bean id="yourCoolBean" class="org.jdong.MyCoolBean">
<property name="anotherBean" ref="thatOtherBean"/>
</bean>
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 {...}
如果是 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" />
您可以像在同一XML文件中引用Bean一样引用它。如果Spring上下文由多个XML文件组成,则所有Bean都是该上下文的一部分,因此共享唯一的命名空间。
如果你只是将bean重构到几个文件中,以避免单个xml文件过大,那么可以直接从当前文件夹中引用它:
<import resource="processors/processor-beans.xml"/>
您还可以通过在代码中加载多个Spring Bean配置文件来实现此操作:
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"Spring-Common.xml", "Spring-Connection.xml","Spring-ModuleA.xml"});
project-classpath/Spring-Common.xml
project-classpath/Spring-Connection.xml
project-classpath/Spring-ModuleA.xml
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>
:
ApplicationContext context =
new ClassPathXmlApplicationContext(Spring-All-Module.xml);
tolitius提供的答案非常详细。 只是Peter Butkovic提到的问题。
对我来说,web.xml块会抛出错误。一个param-value似乎只允许在一个地方。- Peter Butkovic
我遇到了同样的问题,并通过在同一个中使用“,”分割两个路径来解决它。
它看起来像这样
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,
/WEB-INF/daoContext.xml
</param-value>
</context-param>
<import>
?参考 - laahaa