Spring Java config包装注入的地图 [英] Spring Java config wraps injected map
问题描述
我最近从使用Spring的XML配置切换到Java配置,遇到了一个奇怪的问题。
I recently switched from using Spring's XML configuration to its Java configuration and am encountering a strange issue.
XML配置是:
<util:map id="myMap">
<entry key="a" value="aValue"/>
<entry key="b" value="bValue"/>
<entry key="c" value="cValue"/>
</util:map>
<bean id="myBean" class="my.MyClass">
<property name="myMap" ref="myMap"/>
</bean>
Java配置为:
@Bean
public Map<String, Object> myMap() {
Map<String, Object> myMap = new HashMap<>();
myMap.put("a", "aValue");
myMap.put("b", "bValue");
myMap.put("c", "cValue");
return myMap;
}
@Bean
public MyClass myBean(@Qualifier("myMap") final Map<String, Object> myMap) {
MyClass myBean = new MyClass();
myBean.setMyMap(myMap);
return myBean;
}
两个bean都在不同的文件中声明,我将它们分组在这里以使其更容易阅读。地图也包含引用,不仅包括字符串。
Both beans are declared in different files, I grouped them here to make it easier to read. The map contains references too, not only strings.
我希望能够在第二个中使用 myMap
bean而是Spring注入以下地图:
I would expect to be able to use myMap
in the second bean but instead Spring injects the following map:
{ myMap = { a=aValue, b=bValue, c=cValue } }
我不明白为什么Spring将地图包装到另一张地图中,为什么它不表现与XML配置相同。
I don't understand why Spring wraps the map into another map, and why it doesn't behave the same way with the XML configuration.
任何想法?
推荐答案
有一个问题 @Autowired
-ing Map甚至定义了bean名称,因为根据评论你不能使用建议的 @资源
注释通过使用定义bean名称的 @Value
注释,可以有另一种选择:
There is an issue @Autowired
-ing a Map even defining the bean name and since as-per the comments you can't use the suggested @Resource
annotation there is an alternative by using the @Value
annotation defining the bean name:
@Bean
public MyClass myBean(@Value("#{myMap}") final Map<String, Object> myMap) {
//..
}
这篇关于Spring Java config包装注入的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!