3

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?

Paul Podgorsek
  • 2,416
  • 3
  • 19
  • 22
  • Maybe use @Resource like said here : http://stackoverflow.com/questions/13913752/spring-cant-autowire-map-bean ? – Walfrat Dec 09 '16 at 09:13
  • Unfortunately I can't use the `@Resource` solution, as these beans are in different files / different modules. If I use `@Resource`, I end up with a circular reference loop between the modules' contexts. – Paul Podgorsek Dec 09 '16 at 09:16

1 Answers1

4

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) {
//..
}
dimitrisli
  • 20,895
  • 12
  • 59
  • 63