简体   繁体   English

在beans.xml中更新地图条目

[英]Update Map entry in beans.xml

We have xml file with bean definition. 我们有带有bean定义的xml文件。 As this is shared XML file between different modules, We can't change this xml, so as per project need, we decided to update bean definition. 由于这是不同模块之间共享的XML文件,因此我们无法更改此xml,因此根据项目需要,我们决定更新Bean定义。

<bean id="columnMap"
      class="org.springframework.beans.factory.config.MapFactoryBean">
    <property name="sourceMap">
        <map key-type="java.lang.String" value-type="java.lang.String">
            <entry key="Item Id" value="ITEM_ID"/>
        </map>
    </property>
</bean>

Now, need to update this bean in another xml and wanted to add new map entry. 现在,需要在另一个xml中更新此bean,并想要添加新的地图条目。

There are two strategies you can adopt and some really good examples are provided in this stack link ( How can I inject a property value into a Spring Bean which was configured using annotations? ) . 您可以采用两种策略,并且在此堆栈链接中提供了一些非常好的示例( 如何将属性值注入使用注解配置的Spring Bean中? )。
Look at the answer from @Umut Utkan which describes the solution well. 查看@Umut Utkan的答案,它很好地描述了解决方案。

Strategy 1: Add a method invoking factory bean and use that factory to add values to an existing map instead of erroring/overriding. 策略1:添加一个调用工厂bean的方法,并使用该工厂将值添加到现有映射中,而不是错误/覆盖。 However since you cant change the bean definition , i am not going in detail into this (The link has more info on how to achieve it) 但是,由于您不能更改bean的定义,因此我将不做详细介绍(该链接提供了有关如何实现的更多信息)

Strategy 2 : Very simple, set the merge flag of the collection to true as below. 策略2:非常简单,如下所示将集合的合并标志设置为true。

<bean id="columnMap" class="org.springframework.beans.factory.config.MapFactoryBean">
    <property name="sourceMap">
        <util:map>
            <entry key="1" value="1"/>
        </util:map>
    </property>
</bean>
<bean id="specificColumnMap" class="org.springframework.beans.factory.config.MapFactoryBean" parent="columnMap">
    <property name="sourceMap">
        <util:map merge="true">
            <entry key="2" value="2"/>
        </util:map>
    </property>
</bean>

PS : I dont know if this falls in the category of a duplicate question, so i am going to post the answer and let the moderators take a call on that. PS:我不知道这是否属于重复问题的类别,因此我将发布答案,并让主持人对此进行呼叫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM