我发现自己在 applicationContext.xml 和 applicationContext-test.xml 中使用了两个相同的 bean。我希望我的测试上下文能够从我的应用程序上下文继承,以避免重复我自己。
我已经看到很多 Material 表明您可以声明父应用程序上下文并从该上下文中引用 bean,但我找不到有用的示例。任何人都可以帮忙吗?
更新
作为一些背景信息,我的正常应用程序上下文正在 web.xml 中加载:
<context-param>
<description>Application Contexts for Spring</description>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
我的测试应用程序上下文加载在我的单元测试中:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
因此,假设我在常规上下文中有一个 bean:
<bean name="someBean" class="com.foo.MyClass" />
然后,在我的测试应用程序上下文中,我想引用这个 bean。我该怎么做?
更新
根据 skaffman 的建议,我已将 bean 移动到 SharedBeans.xml 文件中并将其导入到我的 applicationContext.xml 中。但是,这会导致 SAXParser 异常:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
我不能确定我做错了什么。 bean 在我的上下文文件中运行良好,我所做的只是剪切并粘贴到新文件中。以下是 SharedBeans.xml 的完整内容:
<bean name="properties" class="com.foo.Properties">
<constructor-arg><value>${module.name}</value></constructor-arg>
<constructor-arg><value>${businessUnit}</value></constructor-arg>
<constructor-arg><value>${product}</value></constructor-arg>
<constructor-arg><value>${env}</value></constructor-arg>
<constructor-arg><value>${machineName}</value></constructor-arg>
<constructor-arg><value>${collectionSet.company}</value></constructor-arg>
<constructor-arg><value>${route.tag}</value></constructor-arg>
<constructor-arg><value>${timeout}</value></constructor-arg>
</bean>
最佳答案
这并没有让我觉得这是父上下文的一个特别好的用例,它主要用于设置层次结构(例如一个根 webapp 上下文,多个子 servlet 上下文)。
对于您的情况,如果您只是将常见的 bean 定义提取到一个单独的文件中,然后 <import>
会更简单易懂。它们放入每个需要它的上下文文件中。你可以用父子上下文来做到这一点,但它会更难理解,不必要的。
好的,举个例子,把你的共享 bean 定义放到一个名为 shared-beans.xml
的文件中。 ,并将其(暂时)放在类路径的顶层,包含:
<bean name="someBean" class="com.foo.MyClass" />
然后,在
applicationContext-test.xml
里面和 /WEB-INF/classes/applicationContext.xml
,添加以下内容:<import resource="classpath:/shared-beans.xml" />
shared-beans.xml
中的所有 bean 定义现在将被导入到每个应用程序上下文中。通过这样做,您不会获得第三个应用程序上下文,您只需从另一个文件导入 bean 定义。
关于spring - 如何声明父应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317690/