首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >继承树的依赖注入

继承树的依赖注入
EN

Stack Overflow用户
提问于 2011-08-05 01:16:22
回答 2查看 2.3K关注 0票数 0

我正在尝试向父类和子类注入一些属性,但我遇到了一些问题。我想从子对象访问注入的commonAddress属性,但同时又想在子对象中注入相对路径。

父类:

代码语言:javascript
复制
public class Parent {
    private String commonAddress;

    public void setCommonAddress(String commonAddress) {
        this.commonAddress = commonAddress;
    }
}

子类:

代码语言:javascript
复制
public class Child1 extends Parent {
    private String relativePath;

    public void setRelativePath(String relativePath) {
        this.relativePath = relativePath;
    }
}

来自src/ applicationContext.xml /applicationContext.xml的资源:

代码语言:javascript
复制
<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的资源:

代码语言:javascript
复制
<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>

测试类:

代码语言:javascript
复制
@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,断言将失败,因此注入不会成功。

代码语言:javascript
复制
<bean id="testParent" class="package.TestParent">
    <property name="parent" ref="parentBean"></property>
</bean>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-05 01:23:50

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

票数 2
EN

Stack Overflow用户

发布于 2011-08-05 01:38:03

公认的答案肯定是正确的,但您也可以考虑在spring xml文件中使用以下内容:

代码语言:javascript
复制
<context:property-placeholder location="classpath:/app.properties" />

然后假设您放置了一个具有正确的名称/值对的属性文件,例如

代码语言:javascript
复制
common.address.value=some value
relative.path.value=some/path/value

您可以在spring xml中执行以下操作:

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6945717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档