Component Map
The complete API consists of 2 annotations.
@ComponentMapKey
@ComponentMapKey
The @ComponentMapKey
annotation defines the method that returns the keys of the map. The annotated method return type is the type of the map's key.
enum class CalculatorOperationType {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
internal interface CalculatorOperation {
@get:ComponentMapKey
val operationType: CalculatorOperationType
fun calculate(a: Int, b: Int): Int
}
Lets implement few operations:
internal class AddOperation : CalculatorOperation {
override val type: CalculatorOperationType = CalculatorOperationType.ADD
override fun calculate(a: Int, b: Int): Int {
return a + b
}
}
internal class MultiplyOperation : CalculatorOperation {
override val type: CalculatorOperationType = CalculatorOperationType.MULTIPLY
override fun calculate(a: Int, b: Int): Int {
return a * b
}
}
No annotations or any library specific code is required in the implementations.
@ComponentMap
Add the @ComponentMap
annotation to map to inject.
class CalculatorServiceImpl : CalculatorService {
@ComponentMap
private lateinit var operations: Map<CalculatorOperationType, CalculatorOperation>
override fun calculate(type: CalculatorOperationType, a: Int, b: Int): Number {
val operationHandler = operations[type] ?: throw IllegalArgumentException("Unknown operation type: $type")
return operationHandler.calculate(a, b)
}
}
The @ComponentMap
annotation can also inject list of beans to the map value:
@ComponentMap
private lateinit var operations: Map<CalculatorOperationType, List<CalculatorOperation>>
By defining the value of the map as List
of beans the library will add all the beans of each key to their relevant list.
For example if you have multiple AnnouncementSubscriber
for each AnnouncementType
just change the type of the map value to List<AnnouncementSubscriber>
and for each AnnouncementType
the list will contain multiple subscribers.
@ComponentMap
private lateinit var subscribers: Map<AnnouncementType, List<AnnouncementSubscriber>>
Last updated