Java Spring IOC覆盖bean的属性

标签 java spring inversion-of-control

我需要 3 个 bean,每个 bean 有 3 个属性,其中 2 个是相关属性 来自另一个 bean 的值 但它们只有 1 个属性不同。我有这样的东西:

<bean id="a" class="myClassPath" scope="prototype">
    <property name='status' value='#{otherBean.myMethod()}'/>
    <property name='code'   value='#{otherBean.myOtherMethod()}'/>
    <property name='typeOf' value='1'/>
</bean>

<bean id="b" class="myClassPath" scope="prototype">
    <property name='status' value='#{otherBean.myMethod()}'/>
    <property name='code'   value='#{otherBean.myOtherMethod()}'/>
    <property name='typeOf' value='2'/>
</bean>

<bean id="c" class="myClassPath" scope="prototype">
    <property name='status' value='#{otherBean.myMethod()}'/>
    <property name='code'   value='#{otherBean.myOtherMethod()}'/>
    <property name='typeOf' value='3'/>
</bean>

这段代码非常多余。我是否可以定义一个 bean 并仅重写属性 typeOf更新

status 和 code 的值在其他使用 Spring 语言的 beans 中定义,这在某种程度上是一个示例。

最佳答案

在这样的场景中利用 bean 模板继承:

    <bean id="yourCommonProperties"  abstract="true" scope="prototype">
        <property name="status" value='#{otherBean.myMethod()}'/>
        <property name="code" value='#{otherBean.myOtherMethod()}'/>
    </bean>

这里我们没有指定类,只是共享公共(public)属性,并在每个 bean 定义中使用 parent 属性引用它:

    <bean id="a" class="myClassPath" parent="yourCommonProperties" scope="prototype">
        <property name='typeOf' value='1'/>
    </bean>
    <bean id="b" class="myClassPath" parent="yourCommonProperties" scope="prototype">
        <property name='typeOf' value='2'/>
    </bean>
    <bean id="c" class="myClassPath" parent="yourCommonProperties" scope="prototype">
        <property name='typeOf' value='3'/>
    </bean>

关于Java Spring IOC覆盖bean的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24739526/

相关文章:

java - 当我调用 Jenkins json api 时,如何判断构建是否正在进行?

java - 将 XML 文件加载到 ecore 模型中(反序列化)

java - Spring MVC 绑定(bind)时 Spring 需要属性

dependency-injection - 自动法。如何获取调用者类类型?

java-8 - java接口(interface)中的默认方法是反模式吗?

java - HashMap 获取对象的值是 "equal"但哈希值不同?

java - PDF/A 验证

java - 如何从响应实体获取正文

java - Jetty 9 与 Spring 2 兼容性

c# - 无法在 Autofac 中注册和添加自动映射器配置文件