2011-08-04 450 views
0

我想一些属性注入到一个父类和子类,我面临的一些问题。我想要从子项访问已注入的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/main /资源的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> 

的从testApplicationContext.xml src/test/resources:

<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); 
    } 

} 

如果我从注释与TestParent的@Autowired parent属性,还有一个问题,因为有2种豆有资格父类型。

如果我显式声明的applicationContext.xml测试豆,断言失败,所以注射是不成功的。

<bean id="testParent" class="package.TestParent"> 
    <property name="parent" ref="parentBean"></property> 
</bean> 

回答

2

我正在使用不带注释的直接XML Spring配置。在你的情况下,我只是指定按名称自动装配。我相信,使用@Qualifier可以达到相同的效果(按名称而不是按类型进行布线)。

+0

谢谢,现在很清楚我。 – DaJackal

1

接受的答案肯定是正确的,但你也可以考虑使用你的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> 
+0

这是一个非常好的主意。谢谢 – DaJackal