Kest

Search

Search the documentation

Fundamentals

Discovery service

Find every method marked with an annotation, so you can build your own framework features.

Many features are really "find everything marked with X and do something with it": run every @Cron method on a schedule, subscribe every @OnEvent method to the event bus, register every @McpTool as a tool. NestJS calls the finder DiscoveryService. In Kest it is Container.methodsWith<A>() and classesWith<A>().

They are backed by metadata the processor generated at build time, so no classpath scanning and no reflection happens at start-up.

Build a small feature of your own: a method annotation that reacts to order events.

// 1. a discoverable annotation of your own
@Discoverable @Target(AnnotationTarget.FUNCTION)
annotation class OnOrderEvent(val type: String)
 
// 2. use it anywhere on a provider
@Injectable class Emails { @OnOrderEvent("paid") fun receipt(order: Order) { ... } }
@Injectable class Stock  { @OnOrderEvent("paid") fun reserve(order: Order) { ... }  @OnOrderEvent("cancelled") fun release(order: Order) { ... } }
 
// 3. read it back, with the instance to call, when the application starts
@Injectable
class OrderEvents(container: Container) : OnApplicationBootstrap {
    private val handlers = container.methodsWith<OnOrderEvent>().groupBy { it.annotation.type }
 
    override fun onApplicationBootstrap() = handlers.forEach { (type, list) ->
        println("$type handled by " + list.joinToString { "${it.owner.simpleName}.${it.method.name}" })
    }
    fun publish(type: String, order: Order) = handlers[type].orEmpty().forEach { it.invoke(order) }       // call each handler
}

methodsWith returns, for each match: the provider instance (owner), the method (its name, parameter names and types, and all its annotations) and the matching annotation (with its values). classesWith does the same for annotations on classes.

Loading diagram…

This is exactly how @Cron, @OnEvent, @MessagePattern, @Processor, @Query, @McpTool and @AiTool work: each package asks for its own annotation and wires the methods. You can add such features to your application, or publish them as your own package.

Notes

  • The annotation must be marked @Discoverable and the class that has the method must be a provider.
  • Parameter names and types are available (it.method.params), so you can build argument binding. Kotlin default values are not visible: treat a nullable parameter as optional.
  • Call it after the container is built (a lifecycle hook, or a constructor that takes the Container).

Read more