Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can create HashMap with Spring but can't create Map

Tags:

spring

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.

like image 771
Kiva Avatar asked Dec 19 '12 09:12

Kiva


People also ask

What is difference between map and HashMap in Java?

HashMap is a non-synchronized class of the Java Collection Framework that contains null values and keys, whereas Map is a Java interface, which is used to map key-pair values.


2 Answers

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;
like image 95
Viral Patel Avatar answered Sep 23 '22 05:09

Viral Patel


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

like image 40
Stanley Avatar answered Sep 25 '22 05:09

Stanley