Skip to main content

Core business logic (Spring)

A class-based, annotation-driven way to write event handlers, as an alternative to GPAL .kts event handlers.

note

Some features of GPAL event handlers are not available in Spring event handlers. See Limitations.

Overview​

genesis-eventhandler-spring-boot-starter lets a Spring Boot application define Genesis event handlers as plain annotated Kotlin or Java classes, instead of writing .kts GPAL event-handler scripts. A class annotated @GenesisEventHandler("EVENT_NAME") (or @GenesisEventController for a group of related events), with @EventValidate/@EventCommit-annotated methods, is scanned at Spring context start-up and registered into the same TypedEventManager registry as GPAL's compiled and scripted event handlers.

From the router's or a connecting client's point of view, an event served by one of these Spring beans looks identical to one served by a GPAL handler, and both mechanisms can coexist in the same process.

This module builds on the Spring application core and depends on genesis-eventhandler and genesis-jpa-base. Handler payloads and validate/commit logic will often touch JPA entities from Data access APIs (JPA).

Choose this module when the surrounding process is already a Spring Boot / JPA application and staying in that programming model outweighs GPAL's greater maturity. It's a second, parallel authoring style for the same event-handler concept, not a replacement — GPAL (genesis-pal-eventhandler, .kts scripts, GPalEventHandler) remains the default for core business logic today.

Exposing an HTTP surface (@RestController) through the Genesis router is not part of this module — that lives in the Spring application core.

Getting set up​

Add a dependency on genesis-eventhandler-spring-boot-starter; genesis-spring-boot-starter, genesis-eventhandler and genesis-jpa-base come transitively. In a standard multi-module project, this goes in the -spring module's build file, server/<project-name>-spring/build.gradle.kts (see Getting Started with Spring: Step 2). There is no separate annotation-processing or KSP step for this module — annotations are read via runtime reflection when a bean is post-processed, not at compile time.

plugins {
id("global.genesis.spring")
}

dependencies {
api("global.genesis:genesis-eventhandler-spring-boot-starter")
}

The module ships its own Spring Boot auto-configuration (GenesisSpringEventHandlerConfig), so adding the dependency is enough — there's nothing to @Import manually. That configuration does expect RightSummaryCache, TypedEventManager, MetaDataRegistry, ServiceRegistry and ServiceDiscovery to already be in the Spring context — the Spring application core's own auto-configuration supplies all of these, so set that up first and there's nothing extra to wire in.

note

This includes logging: Genesis Spring integration only supports Logback, not the Log4j2 backend used elsewhere in Genesis. See Application core: Set-up for what this requires, or Getting Started with Spring: Step 3 for the three-file change.

A handler class doesn't need its own @Component — @GenesisEventHandler, @GenesisEventController and @EventControllerAdvice are themselves meta-annotated @Component, so Spring's component scan picks a class up as soon as it carries one of them. Constructor-inject whatever the handler needs (a repository, RxDb, EventProvider, and so on) the normal Spring way.

A payload can be a Kotlin data class, an ordinary Java class, or a Java record. Every component of a record is mandatory in the event's schema, because a record has no way to declare an optional one.

Example configuration​

The smallest realistic handler is a single event with a commit phase only — no validation, no rights. A payload parameter with no annotation is bound automatically to the incoming event details:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler

data class Update(
val name: String = "",
val qty: Int = 0,
)

@GenesisEventHandler("TOUCH")
class CommitOnlyEventHandler {

@EventCommit
fun commit(details: Update) {
// ... do the work
}
}

@GenesisEventHandler("TOUCH") registers the event with TypedEventManager under that name, the same registry a GPAL handler uses. The event name must match [A-Z][A-Z0-9_]+, or registration fails at start-up. A commit method returning Unit/void (as above) maps to an empty EventReply.EventAck; returning a domain object instead wraps it as EventAck(generated = listOf(thatObject)), and returning a List<*> uses the list directly as generated.

Most handlers need both a validation phase and a commit phase — the equivalent of GPAL's onValidate/onCommit split. The value returned by @EventValidate becomes the "context" available to @EventCommit, injected via a parameter annotated @EventContext (or implicitly, if the parameter's type already matches). The two mechanisms aren't exclusive: a validating handler can also constructor-inject collaborators like EventProvider (see Triggering other events below) and use them from @EventCommit alongside the injected context:

import <packageName>.dao.Widget
import <packageName>.repo.WidgetRepository
import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.EventContext
import global.genesis.eventhandler.spring.annotation.EventValidate
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
import global.genesis.eventhandler.spring.service.blocking.EventProvider

data class Create(val name: String = "", val qty: Int = 0)
data class Created(val id: String)
data class Validated(val normalisedName: String)

@GenesisEventHandler("CREATE")
class ValidatingEventHandler(
private val events: EventProvider,
private val widgets: WidgetRepository, // a Spring Data repository over your own WIDGET table
) {

@EventValidate
fun validate(details: Create): Validated {
check(details.qty > 0) { "qty must be positive" }
return Validated(details.name.uppercase())
}

@EventCommit
fun commit(details: Create, @EventContext ctx: Validated): Created {
widgets.save(Widget(name = details.name, qty = details.qty))
// in-process only; throws if TOUCH isn't registered in this same process
events.trigger("TOUCH", Update(details.name, details.qty))
return Created(id = "${ctx.normalisedName}-${details.qty}")
}
}

@EventContext is optional here, since the commit parameter type (Validated) already exactly matches what @EventValidate returns — the framework injects it either way. The constructor-injected EventProvider is unrelated to that context injection and works the same way on a validating handler as it does on a commit-only one.

Passing type to @GenesisEventHandler marks an event as internal, so the router won't expose it externally:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.EventHandlerType
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler

@GenesisEventHandler("INTERNAL_TOUCH", type = EventHandlerType.INTERNAL)
class InternalEventHandler {

@EventCommit
fun commit(details: Update) {
// ... do the work
}
}

Configuration options​

Handler annotation(s)​

  • @GenesisEventHandler("EVENT_NAME") on a class marks it as a single-event handler. It may declare one @EventValidate method and must declare exactly one @EventCommit method.
  • @GenesisEventController("PREFIX") on a class groups several related events together. Each method annotated @EventMapping("SUFFIX") becomes its own event, registered as PREFIX_SUFFIX. The prefix and each suffix must match [A-Z][A-Z0-9_]+, so a controller with an empty prefix fails registration at start-up. A controller class must not declare @EventValidate/@EventCommit methods — there is no automatic validate/commit split per method inside a controller; a mapped method either handles the request outright or inspects @IsValidateOnly itself (see below).
  • A class cannot carry both @GenesisEventHandler and @GenesisEventController — that combination is rejected at start-up, as is a single handler with no commit method or with more than one commit or validate method, and a controller that maps the same event name twice.
  • EventHandlerType (STANDARD / INTERNAL / APPROVABLE / DEFAULT, which resolves to STANDARD) is settable on the class or per-method, to influence routing and visibility. STANDARD is the default, UI-exposed case. INTERNAL is enforced at the router level: once an event is marked INTERNAL, the router will not expose it externally. APPROVABLE exists only as a value today — there's no supporting machinery for a multi-party approval flow, so setting it doesn't currently change a handler's behaviour (see Limitations).

Parameter-level injection available on a validate/commit/mapping method:

AnnotationEffect
(none)The event payload, unless the parameter type is Event<T> (global.genesis.message.core.event.Event), in which case it's the full envelope instead.
@UserNameInjects the triggering user's username, as a String.
@EventContextInjects the value returned by the paired @EventValidate method. Optional if the parameter type already matches.
@IsValidateOnlyInjects a Boolean reflecting whether the request is a validate=true pre-flight — see below for where this actually takes effect.

A parameter typed as the full envelope has access to more than just the payload — for example, the triggering user's name, off Event.userName:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
import global.genesis.message.core.event.Event

@GenesisEventHandler("UPDATE")
class EnvelopeAwareEventHandler {

@EventCommit
fun commit(details: Event<Update>) {
val triggeredBy = details.userName
val payload = details.details
// ... do the work, e.g. audit `triggeredBy` alongside `payload`
}
}

A single class can also carry static rights checks:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
import global.genesis.eventhandler.spring.annotation.RequiresAnyRight

@GenesisEventHandler("SECURE")
@RequiresAnyRight(["WRITE"])
class AnyRightEventHandler {
@EventCommit
fun commit(details: Update) = Unit
}

@RequiresAnyRight/@RequiresAllRights are checked against RightSummaryCache before the handler method runs; an unauthorised user gets a not-authorised nack and the method body never executes. They can sit on the class and on any handler method: the @EventValidate and @EventCommit methods of a @GenesisEventHandler, or an @EventMapping method of a @GenesisEventController. Every level that carries one applies (logical AND), so the user must pass the class-level check and the check on each of the event's methods. A class-level annotation is inherited by subclasses.

@RequiresAuth(mapName, fields) is also available, intended for row-level/dynamic authorisation against a Genesis authorization map, but it is not enforced today — it's parsed into a model attached to the handler definition and nothing consults it. Don't rely on it for row-level authorisation yet; use @RequiresAnyRight/@RequiresAllRights for anything that must actually be checked.

Validation​

@EventValidate runs on every incoming request for its event, including ones sent with validate=true (a pre-flight check), and its return value becomes the commit-phase context. When a request has validate=true, the framework itself never invokes @EventCommit — it returns whatever @EventValidate produced, converted to an ack or nack, without running the commit method. You don't need to check event.validate yourself — this is handled for both validating and commit-only handlers (a commit-only handler just acks empty instead of running validation logic first).

An exception thrown from @EventValidate on any request, not just validate=true, skips @EventCommit and is mapped to a nack the same way an exception from @EventCommit would be — see Acknowledgement / rejection below.

Bean Validation is partially wired: a parameter can be annotated @jakarta.validation.Valid or @org.springframework.validation.annotation.Validated, and the scanner records that on the parameter definition — but nothing downstream currently runs Bean Validation against it. Putting @Valid on a payload parameter today does not actually validate anything through this module; write your own checks in @EventValidate instead.

Manual validate/commit control​

Occasionally one method needs to see both phases itself rather than have the framework split them — for example, to make a "dry run" flag explicit rather than implicit. @IsValidateOnly supports this, but only on a @GenesisEventController/@EventMapping method:

@GenesisEventController("ADMIN")
class AdminEventController {

@EventMapping("PURGE")
fun purge(details: Update, @IsValidateOnly validateOnly: Boolean): PurgeResult =
PurgeResult(name = details.name, dryRun = validateOnly)
}

On a single @GenesisEventHandler's @EventCommit method, adding an @IsValidateOnly parameter compiles and injects a value, but has no effect on behaviour — the framework always auto-skips that method on a validate=true request before your code runs. If you need manual validate/commit control in one method, it has to be a controller method.

Acknowledgement / rejection​

A handler method's return value is converted to an EventReply automatically:

  • Returning EventReply.EventAck/EventReply.EventNack directly is passed through unchanged.
  • null, Unit, or a void method becomes an empty EventAck.
  • Any other value becomes EventAck(generated = listOf(thatValue)), or EventAck(generated = thatList) if it's a List<*>.

EventReply is a sealed type with three cases, not two: EventAck, EventNack, and EventApprovableAck. The third exists for the approvable-workflow type discussed in Limitations below — not reachable through this module today — but a Kotlin when that branches on EventReply still has to account for it (with an explicit is EventApprovableAck branch or an else) to be exhaustive.

For full manual control, inject an EventProvider (see below) and use its ack(generated), nack(errorCode, message) and warningNack(message) helpers to build the reply by hand.

Exceptions are mapped to nacks through the following mechanisms:

  • A per-handler @EventExceptionHandler([SomeException::class]) method, which takes priority for exceptions thrown by that handler's own methods.
  • A separate class annotated @EventControllerAdvice, with its own @EventExceptionHandler methods, registers globally and is consulted for any handler with no matching handler of its own. An advice class with no @EventExceptionHandler methods fails registration.
  • A custom exception class annotated @EventWarning(status = ...) is treated as a business warning — the resulting EventNack carries it as a warning rather than an error.
  • Any exception that doesn't match one of the above falls back to a default mapping: an IllegalArgumentException produces a nack with error code REQUEST_FAILED and its message as the error text. Any other exception — including ValidatingEventHandler's own IllegalStateException from Example configuration, and the IllegalStateException thrown by commit below when details.name is neither "warn" nor "custom" — is nacked with error code INTERNAL_ERROR and that exception's own message. The one case that doesn't carry its own message is NullPointerException, which gets the generic INTERNAL_ERROR text instead.

An @EventExceptionHandler method must return EventReply and take exactly one Throwable-subtype parameter. On an @EventControllerAdvice class this is checked at start-up:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.EventExceptionHandler
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
import global.genesis.message.core.HttpStatusCode
import global.genesis.message.core.error.StandardError
import global.genesis.message.core.event.EventReply

@EventWarning(status = HttpStatusCode.Conflict)
class WarningException(message: String) : RuntimeException(message)

class CustomException(message: String) : RuntimeException(message)

@GenesisEventHandler("EXPLODE")
class ExplodingEventHandler {

@EventCommit
fun commit(details: Update) {
when (details.name) {
"warn" -> throw WarningException("already exists")
"custom" -> throw CustomException("custom failure")
else -> throw IllegalStateException("boom")
}
}

// Handled locally: takes priority over any global advice for this handler's own exceptions.
@EventExceptionHandler([CustomException::class])
fun onCustom(ex: CustomException): EventReply =
StandardError("CUSTOM", "handled locally: ${ex.message}", HttpStatusCode.BadRequest)
.toEventNackError()
}

EventReply.EventNack's primary constructor takes warning before error (EventNack(warning: List<GenesisError> = ..., error: List<GenesisError> = ...)), which is easy to get backwards positionally from Java — the vararg secondary constructor (EventNack(vararg error: GenesisError)) shown above maps unambiguously onto error instead.

Triggering other events​

A handler can call another event from within its own commit logic by injecting an EventProvider — a suspending variant (global.genesis.eventhandler.spring.service.EventProvider) for suspend call sites, and a blocking one (global.genesis.eventhandler.spring.service.blocking.EventProvider) for everything else, including Java:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
import global.genesis.eventhandler.spring.service.EventProvider
import global.genesis.message.core.event.EventReply

@GenesisEventHandler("CREATE_AND_TOUCH")
class CreateAndTouchEventHandler(
private val events: EventProvider,
) {
@EventCommit
suspend fun commit(details: Create): EventReply {
// in-process only; throws if TOUCH isn't registered in this same process
events.trigger("TOUCH", Update(details.name, details.qty))
return events.ack()
}
}

trigger(eventName, payload) is in-process only — it looks the target event up among the Spring event handlers registered in this process, and throws if none is registered under that name; it does not fall back to a remote call, and it does not find a GPAL event handler in the same process. For a handler registered in a different process, use triggerRemote(eventName, payload) (suspends or blocks for the reply) or triggerAsync(eventName, payload) (fire-and-forget; a nack reply is logged at ERROR), both resolved via ServiceDiscovery. The event name can be given with or without the EVENT_ prefix.

An event triggered from inside a handler method runs as the user who sent the triggering event, so the target's rights checks apply to that user; called outside any handler, it runs as UNKNOWN. It also carries the caller's validate flag: an event triggered from an @EventValidate method, or while handling a validate=true request, is sent with validate=true, so the target only validates.

Suspend handlers — Kotlin only​

Any @EventValidate/@EventCommit/@EventMapping method may be a Kotlin suspend fun; the scanner detects the compiler-injected Continuation parameter and the handler is registered as an asynchronous handler automatically, with no extra annotation needed:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler

@GenesisEventHandler("TOUCH_ASYNC")
class SuspendCommitOnlyEventHandler {

@EventCommit
suspend fun commit(details: Update) {
// ... suspending work, e.g. a coroutine-based repository call
}
}

There is no Java equivalent for this one — suspend handlers are supported in Kotlin only. If you need non-blocking handling from a Java class, look at making the surrounding call non-blocking some other way outside this module; there's no @Async-style alternative offered here.

Limitations​

Spring event handlers have these limitations:

  • There is no transaction control. The annotations have no transactional flag, and the module does not open a transaction for you. A handler method that needs a database transaction has to manage it itself — see Data access APIs (JPA): Transactions for how transaction boundaries and rollback work when a handler uses Spring Data JPA.

  • Approvable workflows are not supported. EventHandlerType.APPROVABLE exists as a value, but the return types needed to drive a multi-party approval flow aren't consumed anywhere in the handler-invocation path. Don't build an approval-based feature on this module today — use GPAL's pending approval workflow instead.

  • @RequiresAuth (row-level/dynamic authorisation) is parsed but not enforced. Only the static @RequiresAnyRight/@RequiresAllRights checks actually run. It compiles and is scanned like any other annotation here:

    import global.genesis.eventhandler.spring.annotation.EventCommit
    import global.genesis.eventhandler.spring.annotation.GenesisEventHandler
    import global.genesis.eventhandler.spring.annotation.RequiresAuth

    @GenesisEventHandler("SECURE")
    class DynamicAuthEventHandler {
    @EventCommit
    @RequiresAuth(mapName = "USER_MAP", fields = ["USERNAME"])
    fun commit(details: Update) = Unit
    }
  • @IsValidateOnly only takes effect on a @GenesisEventController/@EventMapping method, not on a single @GenesisEventHandler's @EventCommit method — see Manual validate/commit control above.

  • Bean Validation (@Valid/@Validated) on a payload parameter has no effect. The annotation is recorded but nothing runs validation against it.

One of these is easy to trip over in practice. The example reuses classes already defined earlier on this page.

@IsValidateOnly still compiles and injects a value on a single handler's @EventCommit method — it's just meaningless, because that method never runs for a validate=true request in the first place:

import global.genesis.eventhandler.spring.annotation.EventCommit
import global.genesis.eventhandler.spring.annotation.GenesisEventHandler

@GenesisEventHandler("TOUCH")
class CommitOnlyEventHandler {

@EventCommit
fun commit(details: Update, @IsValidateOnly validateOnly: Boolean) {
// `validateOnly` is always false here — a validate=true request is auto-acked
// by the framework before this method ever runs, on a single handler.
}
}

Testing​

The dependency and plugin requirements in Getting set up apply to a test the same as to a full process. What differs is the rest: @GenesisSpringTest (see Testing API (Spring)) supplies the five platform beans GenesisSpringEventHandlerConfig expects — RightSummaryCache, TypedEventManager, MetaDataRegistry, ServiceRegistry, ServiceDiscovery — along with everything else a normal Genesis process environment would otherwise provide, so a test doesn't need a real Genesis process running. What it does not supply is your own handler bean, covered below.

The recommended pattern is a real Spring context and a real message client, sending events through the full path — EventClientSync (or its async/Rx equivalents) → TypedEventManager → your handler bean — rather than mocking the framework. This exercises rights checks, the validate/commit split, and exception handling for real, and lets you assert both the reply shape (EventAck/EventNack) and any side effects (a counter, or a row via an injected repository).

See Testing API (Spring) for the annotations and base classes (@GenesisSpringTest, EventClientSync, @UserRight, @ResetTableAfterTest) that support this.

@GenesisSpringTest composes @SpringBootTest(classes = [GenesisTestApplication::class]), and GenesisTestApplication itself carries only @Configuration and @EnableAutoConfiguration — no @ComponentScan. The test context therefore performs no component scanning at all: a hand-written @GenesisEventHandler, @GenesisEventController or @EventControllerAdvice class is never discovered by package position, wherever it lives. It has to be contributed to the context explicitly, for example by listing it alongside GenesisTestApplication:

import global.genesis.springboot.test.GenesisTestApplication

@GenesisSpringTest
@SpringBootTest(classes = [GenesisTestApplication::class, ValidatingEventHandler::class])
class CreateEventHandlerTest {
// ...
}

or via @Import(ValidatingEventHandler::class), or a nested @TestConfiguration that declares it as a @Bean. This is different from a generated Spring Data repository such as Testing API (Spring): A simple example's WidgetRepository, which arrives through autoconfiguration and needs no such step — don't generalise from that example to your own handler classes.

A worked example​

EventClientSync.sendEvent(...) returns an EventReply — the same sealed EventReply.EventAck/EventReply.EventNack type the handler itself returns (see Acknowledgement / rejection). Branch on it to assert the reply shape, and check any side effect (a counter, or a row via an injected repository) inside the ack branch. Reusing Create/ValidatingEventHandler from above:

import <packageName>.repo.WidgetRepository
import global.genesis.message.core.event.EventReply
import global.genesis.springboot.test.GenesisTestApplication
import global.genesis.testsupport.client.eventhandler.EventClientSync

@GenesisSpringTest
@SpringBootTest(
classes = [
GenesisTestApplication::class,
ValidatingEventHandler::class,
CreateAndTouchEventHandler::class,
CommitOnlyEventHandler::class,
],
)
class CreateEventHandlerTest {

@Autowired
lateinit var client: EventClientSync

@Autowired
lateinit var widgetRepository: WidgetRepository

@Test
fun `acks and creates`() {
when (val reply = client.sendEvent(details = Create(name = "widget", qty = 3), messageType = "CREATE")) {
is EventReply.EventAck -> assert(widgetRepository.findByName("widget") != null)
is EventReply.EventNack -> error("expected an ack, got a nack: ${reply.error}")
is EventReply.EventApprovableAck -> error("unexpected: not reachable through this module today")
}
}

@Test
fun `nacks a non-positive quantity`() {
when (val reply = client.sendEvent(details = Create(name = "widget", qty = 0), messageType = "CREATE")) {
is EventReply.EventNack -> assert(reply.error.single().code == "INTERNAL_ERROR")
is EventReply.EventAck -> error("expected a nack, got an ack")
is EventReply.EventApprovableAck -> error("unexpected: not reachable through this module today")
}
}

@Test
fun `also runs the triggered TOUCH handler`() {
// CreateAndTouchEventHandler's commit calls events.trigger("TOUCH", ...) in-process;
// trigger() throws if no TOUCH handler is registered in this process, so reaching an
// ack here is what proves the triggered TOUCH handler actually ran.
when (val reply = client.sendEvent(details = Create(name = "widget", qty = 3), messageType = "CREATE_AND_TOUCH")) {
is EventReply.EventAck -> {
// the TOUCH side effect ran
}
is EventReply.EventNack -> error("expected an ack, got a nack: ${reply.error}")
is EventReply.EventApprovableAck -> error("unexpected: not reachable through this module today")
}
}
}

EventReply.EventNack.error (and .warning) is a List<GenesisError>, each entry exposing code and text — assert on those rather than a message property.

Assert on the side effect and on the nack's error code, not just on whether the reply is an ack or a nack: if the handler isn't in the test context (for example, its @Import or classes = [...] entry is missing), every event to it is nacked with UNKNOWN_MESSAGE_TYPE, so a test that only checks for a nack still passes while testing nothing.

A test can send a validate=true pre-flight request the same way — this is what the @IsValidateOnly parameter reflects on a @GenesisEventController method, and it makes the framework return the @EventValidate result on any handler without running @EventCommit:

client.sendEvent(details = Create(name = "widget", qty = 3), messageType = "CREATE", validate = true)

See also​