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

标签 spring scala dependency-injection

我正在创建一个基于 Spring 的 Scala 项目。我的一个对象需要向其中注入(inject)一个简单的 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的映射]的[java.lang.String]类型的匹配bean:预计至少有1个符合 Autowiring 候选资格的bean对于这种依赖性。

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

最佳答案

我自己也不知道这一点,但实际上发现了这一点:

As a specific consequence of this semantic difference, beans which are themselves defined as a collection or map type cannot be injected via @Autowired since type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection/map bean by unique name

我测试了这个而不是

 @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>

它成功了。

关于spring - 为什么这个 Spring 映射没有注入(inject)到我的 Scala 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957681/

相关文章:

java - spring中的顺序依赖注入(inject)是什么?

spring - Swagger UI 是否支持@PathVariable 绑定(bind)?

java - 如何自定义 spring-messaging websockets 用户订阅?

angularjs - 关于 AngularJS 依赖的困惑

java - 如果属性是 Integer,Spring @Value 总是给出错误

mvvm - 数据源、存储库、 View 模型和 IoC 容器。真的需要存储库吗?

java - 从 jar 文件内启动 postgres docker 失败

scala - 什么是Scala 'killer app'?

Scala 集合循环缓冲区

performance - Scala 中的 @inline 注解真的对性能有帮助吗?