util:map在Spring中拾取地图类型的每个bean

Cra*_*aig 19 spring map

我有一个Spring地图问题让我流泪.

我的春天看起来像这样:

<?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-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    ">

   <util:map id="mockMap">
        <entry key="userTest1" value="test1"/>
        <entry key="userTest2" value="test2"/>
        <entry key="userTest3" value="test6"/>
    </util:map>
</beans>
Run Code Online (Sandbox Code Playgroud)

然后我自动连接的代码如下(省略了相关部分):

@Autowired
@Resource(name="mockMap")
Map<String, String> testMap;

@Test
public void testGetGearListActivityOK() {
    for (String key : testMap.keySet()) {
        System.out.println("key = " + key);
    }
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这实际上会给我一个错误的自动装配步骤,说没有匹配类型字符串的bean.但是,如果我将单元测试中的地图更改为Map,那么我得到以下输出:

[junit] key = mockMap
[junit] key = org.springframework.context.annotation.internalConfigurationAnnotationProcessor
[junit] key = org.springframework.context.annotation.internalAutowiredAnnotationProcessor
[junit] key = org.springframework.context.annotation.internalRequiredAnnotationProcessor
[junit] key = org.springframework.context.annotation.internalCommonAnnotationProcessor
[junit] key = systemProperties
[junit] key = systemEnvironment
[junit] key = messageSource
[junit] key = applicationEventMulticaster
[junit] key = lifecycleProcessor
Run Code Online (Sandbox Code Playgroud)

我还没有能够将条目的关键部分显示为实际显示为关键字.如果我将地图更改回Map​​并将一些地图添加到我的春天,那么地图将填充这些地图,使用他们的ID作为键.

我在这里很困惑,并且在过去使用了春天相当的数量.如果有人知道这里到底发生了什么,我将非常感激.

提前致谢.

另外,我看到了这个问题:使用util模式自动连接List会产生NoSuchBeanDefinitionException

但是解决方案是使用@Resource,我已经在做了..

小智 25

删除@Autowired并仅使用@Resource(name ="mockMap")

  • Autowired正在覆盖资源,因此Spring正在寻找它所具有的第一个Map对象,恰好是Spring上下文.这就是为什么你得到你提到的键作为输出的原因. (3认同)
  • 实际上,如果您在任何集合上使用@Autowired,它会查找与您的限定符匹配的任何bean(如果没有限定符,则查找该类型的所有bean)并将它们添加到集合中。如果您没有该类型的任何 bean,您将在该对象的自动装配过程中收到“未找到任何 bean,至少有一个预期的”异常。 (2认同)