In this quick start guide, we'll review a simple use-case for Spring ComponentMap, injecting a map of beans.
Before getting started, make sure you have followed the installation steps outlined in the Installation guide.
Bean Interface
We start by defining the interface of the map value beans ActionHandler. The injected map will be of type Map<String, ActionHandler>.
interfaceActionHandler {/** * The action that this handler can handle, add the `@ComponentMapKey` annotation to the getter in order to register it
*/@get:ComponentMapKeyval type: Stringfunhandle()}
publicinterfaceActionHandler { /** * The action that this handler can handle, add the `@ComponentMapKey` annotation to the getter in order to register it
*/ @ComponentMapKeyStringgetType();voidhandle();}
The @ComponentMapKey annotation defines the method that returns the keys of the map, therefore its return type is the type of the map's key.
We will continue by implementing a few ActionHandler beans:
@ComponentclassActionHandler1 : ActionHandler {overrideval type ="type1"overridefunhandle() {println("ActionHandler1") }}@ComponentclassActionHandler2 : ActionHandler {overrideval type ="type2"overridefunhandle() {println("ActionHandler2") }}
Injecting the map is as simple as adding @ComponentMap annotation to map.
@ComponentclassActionHandlerMap {/** * The `@ComponentMap` annotation will automatically populate this map with all beans of type `ActionHandler` */@ComponentMapprivatelateinitvar handlers: Map<String, ActionHandler>funhandle(type: String) { handlers[type]?.handle() }}
@ComponentpublicclassActionHandlerMap { /** * The `@ComponentMap` annotation will automatically populate this map with all beans of type `ActionHandler` */ @ComponentMapprivateMap<String,ActionHandler> handlers;publicvoidhandle(String type) {handlers.get(type).handle(); }}
That's it! We have injected a map with our own keys. Simple and easy.