1

我有 2 个 Maven 项目、一个网络应用程序和一个“服务”项目。我正在使用弹簧将所有东西连接在一起。我想在我的 application-context.xml 中创建一个地图,并将其注入我的班级。当我尝试启动我的 Web 应用程序时,我收到一条错误消息。

这是我的课:

 @Named("tranformer")
 public class IdentifierTransformerImpl implements IdentifierTransformer {


private Map<String, String> identifierMap;

@Inject
public IdentifierTransformerImpl(
        @Named("identifierMap")
        final Map<String, String> identifierMap) {
            this.identifierMap= identifierMap;
}

和 application-context.xml:

    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd"

  <util:map id="identifierMap" map-class="java.util.HashMap">
    <entry key="Apple" value="fruit"/>
    <entry key="BlackBerry" value="fruit"/>
    <entry key="Android" value="robot"/>
   <util:map>

  <context:component-scan base-package="com.example" />

我收到以下错误:

 ..... 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: {@javax.inject.Named(value=identifierMap)

当我在我的应用程序上下文中定义一个字符串并且构造函数将它注入到一个类中时,这有效,我怎样才能对地图做同样的事情?

4

3 回答 3

2

I think Map collection is not supported by @Inject or @Autowired annotation (see: Spring can't autowire Map bean). However I managed to autowire a Map by annotating it as a resource as suggested by that answer. Try this:

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

The downside is ofcourse that isn't a constructor autowiring, but a field. I haven't found a way of doing it through constructor autowiring yet

于 2013-04-30T01:29:30.293 回答
0

如果那是您的 xml 文件的直接复制/粘贴,那么您并没有结束您的<util:map>标签。你/在第二个中缺少一个。

于 2013-05-04T23:15:50.120 回答
-1

With constructor injection.

@Inject
public IdentifierTransformerImpl(
    @Value(value = "#{identifierMap}")
    final Map<String, String> identifierMap) {
        this.identifierMap= identifierMap;
}

Not ideal but Spring declines to provide a better option.

Check out more details at https://jira.spring.io/browse/SPR-8519

于 2015-11-21T20:01:57.830 回答