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.
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 @Component
s, 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;
}
}
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;
}
}
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