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.
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With