我有两个通过<util:map>
定义的地图(一个要使用,另一个是供其他人使用的参考地图)。我想将一个地图的值引用(导入/合并)到另一个地图
CommonMap
-> "someKey" : "someValue"
-> "someOtherKey" : "someOtherValue"
Map1
-> grab all key value pairs in 'CommonMap'
我尝试了一个更简单的示例,该示例定义公用映射并尝试引用它以进行属性注入:
编辑#2最初的问题已解决,这要归功于下面的答案以及现在的主要问题
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="mainBean" class="SpringTest.SpringTest">
<property name="myBean" ref="myFirstBean"/>
</bean>
<bean id="myFirstBean" class="SpringTest.MyBean">
<constructor-arg value="Hello!"/>
<property name="myMap" ref="myLookup" />
</bean>
<util:map id="myLookup">
<entry key="myKey" value="142"/>
<entry key="myOtherKey" value="7"/>
</util:map>
如何创建第二个
<map>
并引用其中的所有myLookup
值?编辑#3我尝试过的更多细节
试试这个
<bean id="myFirstBean" class="SpringTest.MyBean">
<constructor-arg value="Hello!"/>
<property name="myMap" ref="myLookup" />
</bean>
<util:map id="commonLookup">
<entry key="myKey" value="142"/>
<entry key="myOtherKey" value="7"/>
</util:map>
<bean id="myLookup" parent="commonLookup">
<util:map merge="true" />
</bean>
但是得到这个错误
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 25 in XML document from class path resource [configuration-spring.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 40; cvc-complex-type.3.2.2: Attribute 'merge' is not allowed to appear in element 'util:map'.
最佳答案
根据https://stackoverflow.com/a/13243395/3817953:
<bean id="myFirstBean" class="SpringTest.MyBean">
<constructor-arg value="Hello!" />
<property name="myMap" ref="myLookup" />
</bean>
<bean id="commonLookup"
class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map>
<entry key="myKey" value="142" />
<entry key="myOtherKey" value="7" />
</map>
</property>
</bean>
<bean id="myLookup" parent="commonLookup"
class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map merge="true">
<entry key="myLookupKey" value="12" />
</map>
</property>
</bean>