Quick Start

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>.

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()
}

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")
    }
}

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()
    }
}

That's it! We have injected a map with our own keys. Simple and easy.

Code Examples

Additional code examples are available here.

Last updated