19

我有一个让我流泪的 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>

然后我自动装配的代码如下(不相关部分省略):

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

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

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

[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

我还不能让条目的关键部分实际显示为关键。如果我将地图改回 Map 并将一些添加到我的 spring 中,那么地图会使用它们的 id 作为键填充这些内容。

我在这里很困惑,过去使用过相当数量的弹簧。如果有人知道这里到底发生了什么,我将不胜感激。

提前致谢。

另外,我看到了这个问题:Auto-wiring a List using util schema give NoSuchBeanDefinitionException

但是那里的解决方案是使用@Resource,我已经在这样做了..

4

3 回答 3

26

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

于 2012-09-07T19:22:38.680 回答
1

你不能自动装配这样的集合。

但是,您可以尝试以下方法:

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

甚至:

@Value("#{mockMap}")
private Map<String, String> testMap;

检查spring 文档,提示部分:

本身定义为集合或映射类型的 bean 不能通过 @Autowired 注入,因为类型匹配不适用于它们。对此类 bean 使用 @Resource

于 2016-09-07T05:28:37.187 回答
0

仅使用 @Resource 并将配置中的“testMap”更改为“mockMap”

于 2013-11-26T07:17:50.147 回答