Can spring @Autowired Map?

You can create an automatically initialized map with keys of your choice using Spring Java configuration:

In class annotated with @Configuration annotation:

@Autowired
private List<ISendableConverter> sendableConverters;

@Bean
public Map<String, ISendableConverter> sendableConvertersMap() {
    Map<String, ISendableConverter> sendableConvertersMap = new HashMap<>();
    for (ISendableConverter converter : sendableConverters) {
        sendableConvertersMap.put(converter.getType(), converter);
    }
    return sendableConvertersMap;
}

Than you inject this map with:

@Resource()
private Map<String, ISendableConverter> sendableConverters;

You can optionally add some selector string to your @Resource annotation if you have defined more maps of the same type.

This way all you have to do is implement ISendableConverter by your spring bean and it will automatically appear in Map defined above.
You don’t need to create map items by hand for each implementation.

Leave a Comment