Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Java config wraps injected map

Tags:

java

spring

I recently switched from using Spring's XML configuration to its Java configuration and am encountering a strange issue.

The XML configuration was:

<util:map id="myMap">
    <entry key="a" value="aValue"/>
    <entry key="b" value="bValue"/>
    <entry key="c" value="cValue"/>
</util:map>

<bean id="myBean" class="my.MyClass">
    <property name="myMap" ref="myMap"/>
</bean>

The Java configuration is:

@Bean
public Map<String, Object> myMap() {

    Map<String, Object> myMap = new HashMap<>();
    myMap.put("a", "aValue");
    myMap.put("b", "bValue");
    myMap.put("c", "cValue");

    return myMap;
}

@Bean
public MyClass myBean(@Qualifier("myMap") final Map<String, Object> myMap) {

    MyClass myBean = new MyClass();
    myBean.setMyMap(myMap);

    return myBean;
}

Both beans are declared in different files, I grouped them here to make it easier to read. The map contains references too, not only strings.

I would expect to be able to use myMap in the second bean but instead Spring injects the following map:

{ myMap = { a=aValue, b=bValue, c=cValue } }

I don't understand why Spring wraps the map into another map, and why it doesn't behave the same way with the XML configuration.

Any ideas?

like image 881
Paul Podgorsek Avatar asked Aug 01 '26 02:08

Paul Podgorsek


1 Answers

There is an issue @Autowired-ing a Map even defining the bean name and since as-per the comments you can't use the suggested @Resource annotation there is an alternative by using the @Value annotation defining the bean name:

@Bean
public MyClass myBean(@Value("#{myMap}") final Map<String, Object> myMap) {
//..
}
like image 135
dimitrisli Avatar answered Aug 03 '26 17:08

dimitrisli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!