我创建了一些bean,它们都使用类似的模式进行bean实例化。顶级对象都非常相似,但它们包含的对象因字符串构造函数参数而异。除了THIS CHANGES A
的两个实例和THIS CHANGES B
的一个实例之外,每个顶级bean中的所有内容都是相同的。下面是我的一个豆子。除了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的参考。
答案 0 :(得分: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”配置自己的值。
请注意,“parent”没有类,因此无法实例化。另请注意,“child1”和“child2”可以是同一个抽象bean定义的子类,而它们是完全不同的类 - 这个层次结构与类层次结构无关。