Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Java Configuration - how do create a map of enums to beans-references

Tags:

java

spring

with Java based configuration, i am trying to convert a map that maps enums to bean references to be in pure java config (currently in XML & works) but can't seem to find anything in the documentations;

Currently, my XML like so;

<util:map id="colourHanders" key-type="com.example.ColourEnum"
          value-type="com.example.ColourHandler">
    <entry key="white" value-ref="whiteColourHandler"/>
    <entry key="blue" value-ref="blueColourHandler"/>
    <entry key="red" value-ref="redColourHandler"/>
</util:map>

I'm sure it is easy but again, can't find anything on the subject of how to represent this in Pure Java (so I don't have any XML configuration files)..

Note; the ColourHandler beans are created using the @Component annotation, e.g..

@Component
public class RedColourHandler implements ColourHander{
.....
}

and the map of colourHandlers is referenced as so;

@Resource(name="colourHandlers")
    private Map<ColourHandlerEnum, ColourHandler> colourHandlers;

Thanks,

Ian.

like image 539
Mannie Avatar asked Nov 08 '12 16:11

Mannie


2 Answers

You probably want something like this:

@Configuration
public class MyConfiguration {
    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteHandler());
        // etc
        return map;
    }

    @Bean public ColourHandler whiteHandler() {
        return new WhiteHandler();
    }
}

If you need to keep your handlers as @Components, then you can autowire them into the configuration class:

@Configuration
public class MyConfiguration {
    @Autowired private WhiteColourHandler whiteColourHandler;

    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteColourHandler);
        return map;
    }
}
like image 101
hertzsprung Avatar answered Oct 27 '22 14:10

hertzsprung


Since you already have a unique class/@Component for each ColorHandler, I would just let Spring figure out what to use (no need for @Autowire injection nor any additional creation methods):

@Configuration
public class MyConfiguration {
    @Bean public Map<ColourEnum, ColourHandler> colourHandlers(
            WhiteColourHandler whiteHandler, 
            BlueColourHandler blueHandler, 
            RedColourHandler redHandler) {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteHandler);
        map.put(BLUE, blueHandler);
        map.put(RED, redHandler);
        return map;
    }
}
like image 39
inor Avatar answered Oct 27 '22 14:10

inor