0

我有一些我创建的 bean,它们都使用类似的模式进行 bean 实例化。顶级对象都非常相似,但它们包含的对象因字符串构造函数参数而异。除了两个实例THIS CHANGES A和一个THIS CHANGES B. 下面是我的一颗豆子。THIS CHANGES除数值外,其他完全相同。

<bean id="mover1" class="CustomDataMover">
        <constructor-arg ref="session"/>
        <constructor-arg>
            <bean class="DataCache">
                <constructor-arg>
                    <bean class="AllValuesReader">
                        <constructor-arg ref="databaseConnector"/>
                        <constructor-arg value="THIS CHANGES A"/>
                        <constructor-arg value="v1"/>
                        <constructor-arg value="v2"/>
                    </bean>
                </constructor-arg>
            </bean>
        </constructor-arg>
        <constructor-arg ref="customUpdate"/>
        <constructor-arg value="THIS CHANGES B"/>
        <constructor-arg>
            <bean class="ValueGenerator">
                <constructor-arg>
                    <bean class="LatestValueRetriever">
                        <constructor-arg ref="databaseConnector"/>
                        <constructor-arg value="v3"/>
                        <constructor-arg value="v4"/>
                        <constructor-arg value="THIS CHANGES A"/>
                    </bean>
                </constructor-arg>
            </bean>
        </constructor-arg>
</bean>

如何减少 bean 中的重复数量?我正在寻找某种方法来制作某种模板。另外,请注意我确实引用了其他 bean。

4

1 回答 1

5

您可以使用抽象 bean 定义作为模板来减少重复。例如:

<bean id="parent" abstract="true">
    <constructor-arg value="ARG0"/>

    <property name="propertyA" value="A"/>
    <property name="propertyB" value="B"/>
    <property name="propertyC" ref="beanC"/>
</bean>

<bean id="child1" class="SomeClass" parent="parent">
    <property name="propertyD" value="D1"/>
</bean>

<bean id="child2" class="SomeOtherClass" parent="parent">
    <property name="propertyD" value="D2"/>
</bean>

bean "child1" 和 "child2" 将共享来自 "parent" 的 arg0、"propertyA"、"propertyB" 和 "propertyC" 的值,并且仍然能够为 "propertyD" 配置它们自己的值。

请注意,“父级”没有类,因此无法实例化。另请注意,“child1”和“child2”可以是相同抽象 bean 定义的子级,但可以是完全不同的类——这种层次结构与类层次结构无关。

于 2012-02-16T16:41:29.980 回答