Spring无法自动连线Map Bean

我在Spring定义了这样的地图:

<util:map id="AdditionalParams" scope="prototype" map-class="java.util.HashMap" 

key-type="java.lang.String" value-type="java.lang.String">

<entry key="Start" value="12345" />

<entry key="Finish" value="12365" />

</util:map>

然后,我将该bean自动装配为定义为的属性:

private @Autowired @Qualifier(value = "AdditionalParams") Map<String, String> additionalParams;

这样做时,会抛出一个异常,说:

`Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘DutyCreator’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map DutyCreator.additionalParams; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=AdditionalParams)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=AdditionalParams)}`

有任何想法吗?

回答:

从Spring 4.3开始,@Autowired 可以注入列表和地图,问题中的给定代码将起作用:

也就是说,从4.3版本开始,@Autowired只要元素类型信息保留在@Bean返回类型签名或集合继承层次结构中,就可以通过Spring的类型匹配算法来匹配集合/映射和数组类型。

但是在较低的Spring版本中,你无法自动连接这样的集合。但是,你可以执行以下操作:

@Resource(name="AdditionalParams")

private Map<String, String> additionalParams;

甚至:

@Value("#{AdditionalParams}")

private Map<String, String> additionalParams;

检查spring文档,提示部分:

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

以上是 Spring无法自动连线Map Bean 的全部内容, 来源链接: utcz.com/qa/412505.html

回到顶部