我需要 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/