문제

I have 2 maven projects, a web-app, and a 'service' project. I am using spring to wire everything together. I would like to create a map in my application-context.xml, and have that injected into my class. When I try to start my web application I get an error message.

Here is my class:

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

and the 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" />

I get the following error:

 ..... 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)

This works when I define a string in my application-context, and constructor inject it into a class, how can I do the same for a map?

도움이 되었습니까?

해결책

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

다른 팁

If that is a direct copy/paste of your xml file, you aren't ending your <util:map> tag. You're missing a / in the second one.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top