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 .
Bean Interface
We start by defining the interface of the map value beans ActionHandler. The injected map will be of type Map<String, ActionHandler>.
interface ActionHandler {
/**
* The action that this handler can handle, add the `@ComponentMapKey` annotation to the getter in order to register it
*/
@get:ComponentMapKey
val type: String
fun handle()
}
public interface ActionHandler {
/**
* The action that this handler can handle, add the `@ComponentMapKey` annotation to the getter in order to register it
*/
@ComponentMapKey
String getType();
void handle();
}
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:
@Component
class ActionHandler1 : ActionHandler {
override val type = "type1"
override fun handle() {
println("ActionHandler1")
}
}
@Component
class ActionHandler2 : ActionHandler {
override val type = "type2"
override fun handle() {
println("ActionHandler2")
}
}
@Component
public class ActionHandler1 implements ActionHandler {
@Override
public String getType() {
return "type1";
}
@Override
public void handle() {
System.out.println("ActionHandler1");
}
}
@Component
public class ActionHandler2 implements ActionHandler {
@Override
public String getType() {
return "type2";
}
@Override
public void handle() {
System.out.println("ActionHandler2");
}
}
Injecting The Map
Injecting the map is as simple as adding @ComponentMap annotation to map.
@Component
class ActionHandlerMap {
/**
* The `@ComponentMap` annotation will automatically populate this map with all beans of type `ActionHandler`
*/
@ComponentMap
private lateinit var handlers: Map<String, ActionHandler>
fun handle(type: String) {
handlers[type]?.handle()
}
}
@Component
public class ActionHandlerMap {
/**
* The `@ComponentMap` annotation will automatically populate this map with all beans of type `ActionHandler`
*/
@ComponentMap
private Map<String, ActionHandler> handlers;
public void handle(String type) {
handlers.get(type).handle();
}
}
That's it! We have injected a map with our own keys. Simple and easy.