25
votes

I can do this in my applicationContext with Spring (3.0.5):

<bean id="map" class="java.util.HashMap" scope="prototype" >
    <constructor-arg>
        <map key-type="java.lang.String" value-type="java.lang.String">
            <entry key="Key 1" value="1" />
            <entry key="Key 2" value="2" />
        </map>
    </constructor-arg>
</bean>

And in my controller, I can autowired my map like this:

@Autowired
@Qualifier("map")
private HashMap<String, String> map;

It works fine, but if I do this:

@Autowired
@Qualifier("map")
private Map<String, String> map;

I get that:

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=map)}

My question is: Why I can't autowired my map with the interface when I can with the implementation ?

Thanks.

2
don't have a bean id of map, thats confusingNimChimpsky
the real problem is: a map shouldn't be a spring bean at all in the first place. services should be beans, data shouldn't. If you really want a map bean, create a bean that holds a map and inject that.Sean Patrick Floyd
@SeanPatrickFloyd why not you can inject anything and get benefits. There are no negative effects are there ? (assuming you give it a descriptive name)NimChimpsky

2 Answers

36
votes

While declaring a bean of type collection, one cannot inject it via @Autowired. See below documentation from Spring:

4.11.3 Fine-tuning annotation-based autowiring with qualifiers

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.

Thus instead of @Autowired, use @Resource:

@Resource
@Qualifier("map")
private Map<String, String> map;
11
votes

Try to use @Resource instead of @Autowired

@Resource(name="map") 
private HashMap<String, String> map;

Check out the tip in 3.9.3 Fine-tuning annotation-based autowiring with qualifiers of Spring's documentation