Kiva
Kiva

Reputation: 9363

Can create HashMap with Spring but can't create Map

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.

Upvotes: 25

Views: 27840

Answers (2)

Viral Patel
Viral Patel

Reputation: 8601

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;

Upvotes: 36

Stanley
Stanley

Reputation: 5137

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

Upvotes: 11

Related Questions