为什么这个Spring映射没有注入到我的Scala对象中?

时间:2012-08-14 17:32:59

标签: spring scala dependency-injection

我正在创建一个基于Spring的Scala项目。我的一个对象需要一个简单的Map[String, String]注入其中。我有以下代码:

applicationContext.xml

<?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:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:device="http://www.springframework.org/schema/mobile/device"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mobile/device http://www.springframework.org/schema/mobile/device/spring-mobile-device-1.0.xsd">

  <util:map id="validHosts">
    <entry key="host1.domain.com" value="queue-1" />
    <entry key="host2.domain.com" value="queue-2" />
  </util:map>

</beans>

HostMapper.Scala

import scala.collection.JavaConversions._

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class HostMapper() {

  @Autowired private var validHosts:java.util.Map[String, String] = null

}

运行此应用时,我在启动时收到以下错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到类型[java.lang.String]的匹配bean,用于依赖[map with value type java.lang.String]:期望至少有一个bean有资格作为autowire候选者对于这种依赖。

我尝试将键和值类型明确声明为java.lang.String,但这没有效果。我可能做错了什么想法?

1 个答案:

答案 0 :(得分:4)

我自己并不知道,实际上发现了这个:

  

作为此语义差异的特定结果,无法通过@Autowired注入本身定义为集合或映射类型的bean,因为类型匹配不适用于它们。对这样的bean使用@Resource,通过唯一名称引用特定的集合/映射bean

我测试了这个而不是

 @Autowired

我用过:

 @Resource
 private Map<String, String> validHosts;


 <util:map id="validHosts" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="host1.domain.com" value="queue-1" />
    <entry key="host2.domain.com" value="queue-2" />
</util:map>

它有效。