我正在尝试向父类和子类注入一些属性,但我遇到了一些问题。我想从子对象访问注入的commonAddress属性,但同时又想在子对象中注入相对路径。
父类:
public class Parent {
private String commonAddress;
public void setCommonAddress(String commonAddress) {
this.commonAddress = commonAddress;
}
}子类:
public class Child1 extends Parent {
private String relativePath;
public void setRelativePath(String relativePath) {
this.relativePath = relativePath;
}
}来自src/ applicationContext.xml /applicationContext.xml的资源:
<bean id="parentBean" class="package.Parent">
<property name="commonAddress" ref="commonAddressString"/>
</bean>
<bean id="childBean" class="package.Child1">
<property name="relativePath" ref="relativePathString"/>
</bean>来自src/test/ testApplicationContext.xml的资源:
<bean id="commonAddressString" class="java.lang.String">
<constructor-arg>
<value>CommonAddressValue</value>
</constructor-arg>
</bean>
<bean id="relativePathString" class="java.lang.String">
<constructor-arg>
<value>RelativePathValue</value>
</constructor-arg>
</bean>测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class TestParent {
private Parent parent;
public void setParent(Parent parent) {
this.parent = parent;
}
@Test
public void testParentInjectionInTestClass(){
Assert.assertNotNull(parent);
}
}如果我用@Autowired注释TestParent中的parent属性,就会出现问题,因为有两个bean符合父类型的条件。
如果我在applicationContext.xml中显式声明测试bean,断言将失败,因此注入不会成功。
<bean id="testParent" class="package.TestParent">
<property name="parent" ref="parentBean"></property>
</bean>发布于 2011-08-05 01:23:50
我直接使用不带注释的XML Spring配置。在您的情况下,我只需指定按名称自动布线。我相信使用@Qualifier注释可以达到同样的效果(按名称连接,而不是按类型连接)。
发布于 2011-08-05 01:38:03
公认的答案肯定是正确的,但您也可以考虑在spring xml文件中使用以下内容:
<context:property-placeholder location="classpath:/app.properties" />然后假设您放置了一个具有正确的名称/值对的属性文件,例如
common.address.value=some value
relative.path.value=some/path/value您可以在spring xml中执行以下操作:
<bean id="parentBean" class="package.Parent">
<property name="commonAddress" value="${common.address.value}"/>
</bean>
<bean id="childBean" class="package.Child1">
<property name="relativePath" ref="${relative.path.value}"/>
</bean>https://stackoverflow.com/questions/6945717
复制相似问题