Arcadia Editions Modulith: Spring Boot Kotlin
Section titled “Arcadia Editions Modulith: Spring Boot Kotlin”The same six bounded contexts and the same models as the Java modulith, generated as Kotlin: one Spring Modulith module per context, in-process events with a transactional outbox. The structure is generated from the ZDL models with ZenWave SDK and the Kotlin backend application customization. The behavior of the place-order flow was implemented with zenwave-sdd (HITL models, AFK implementation).
Source code: arcadia-editions-modulith-service-kotlin. Models: arcadia-editions-modulith-api.
| Area | Technology |
|---|---|
| Language | Kotlin 2.5.x (kapt) on JDK 25 |
| Framework | Spring Boot 4.0.x |
| Modular monolith | Spring Modulith 2.0.x + JDBC event publication registry (no broker) |
| Persistence | Spring Data JPA + PostgreSQL |
| Mapping | MapStruct (via kapt) |
| Formatting | Spotless + ktlint |
Modules
Section titled “Modules”One module per bounded context. Only orders.checkout exposes an API to the outside (REST, generated from OpenAPI). The other modules react to events published in-process, and three steps call another module directly (startOrderCheckout, confirmOrder and expireReservation). catalog.products is not part of the place-order flow. The arrows come from @listener and @calls in the models.
Domain models
Section titled “Domain models”The models are shared with the Java and Quarkus moduliths: one ZDL per bounded context in arcadia-editions-modulith-api. See the Java page for all of them.
The aggregate
Section titled “The aggregate”Start with the data. This is the Order aggregate of Orders Checkout, with its lifecycle:
orders-checkout-domain-model.zdl: Order aggregate
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}Its rules and @invariant
Section titled “Its rules and @invariant”The rules and @invariants are the part of the model the generator does not turn into code. They are the natural-language spec the coding agents implemented the behavior against. These are the rules of Order:
orders-checkout-domain-model.zdl: rules (Order)
rules (Order) { @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency" @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change" @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing" @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it" @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected" @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED" singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"}orders-checkout-domain-model.zdl: service and rules
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @listener(zdl: CatalogInventoryZdl, event: StockReleased) @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelled
@get("/{id}") getOrder(id) Order?}
rules { reserveBeforePersist "startOrderCheckout reserves stock (InventoryService.reserveStock) before persisting the Order; all lines are reserved or none" confirmOnlyWithHeldStock "An Order is confirmed only if InventoryService.confirmStockReservation answers CONFIRMED: every line is still RESERVED" rejectedConfirmationVoids "A confirmation refused because the Order is CANCELLED or its stock is NOT_HELD emits OrderConfirmationRejected, so payments voids the authorization" cancellationOwner "OrdersCheckout is the only owner of OrderCancelled: it cancels only in reaction to StockReleased" cancellationReasonFromRelease "cancellationReason is the StockReleaseReason carried by StockReleased" orderCreatedCarriesAmount "OrderCreated.amount and currency are Order.totalAmount and currency: they are the amount payments authorizes"}ZenWave scripts
Section titled “ZenWave scripts”Compared to the Java modulith, the script imports the kotlin-backend-application customization and sets Kotlin templates on each plugin:
zenwave-scripts.zw
@import("io.zenwave360.sdk.plugins.customizations:kotlin-backend-application:2.9.0")@import("com.arcadiaeditions.modulith.application.arcadia-editions-modulith:service-all:0.10.3")config {
basePackage "com.arcadiaeditions" layout.commonPackage "{{basePackage}}.common" layout.entitiesCommonPackage "{{commonPackage}}.domain" layout.domainEventsCommonPackage "{{commonPackage}}.domain.events" layout.coreImplementationCommonPackage "{{commonPackage}}" layout.coreImplementationMappersCommonPackage "{{commonPackage}}.mappers" layout.infrastructureRepositoryCommonPackage "{{commonPackage}}" layout.infrastructureEventsCommonPackage "{{commonPackage}}" layout.adaptersWebCommonPackage "{{commonPackage}}" layout.adaptersWebMappersCommonPackage "{{commonPackage}}.mappers" layout.adaptersCommandsCommonPackage "{{commonPackage}}.commands" layout.adaptersCommandsMappersCommonPackage "{{commonPackage}}.commands.mappers" layout.adaptersEventsCommonPackage "{{commonPackage}}.events" layout.adaptersEventsMappersCommonPackage "{{commonPackage}}.events.mappers"
useJSpecify true useJMolecules true useSpringModulith true implementEventListeners true includeEmitEventsImplementation true
// --force removed 2026-11-17: would overwrite AFK-implemented generated-once files
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-products-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/fulfillment-shipping-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/notifications-consumer-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" } BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/payments-processing-domain-model.zdl" }
/** Generates Spring MVC controllers from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.OpenAPIControllersKotlinTemplates()" zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO } SpringWebTestClientPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.SpringWebTestClientKotlinTemplates()" zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO } }}zenwave-scripts.zw: Kotlin templates
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.BackendApplicationKotlinTemplates()" haltOnFailFormatting false zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl" }zenwave-scripts.zw: controllers and API tests
/** Generates Spring MVC controllers from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.OpenAPIControllersKotlinTemplates()" zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO } SpringWebTestClientPlugin { templates "new io.zenwave360.sdk.plugins.kotlin.SpringWebTestClientKotlinTemplates()" zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl" openapiFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-openapi.yml" openApiModelNameSuffix DTO }Generated code
Section titled “Generated code”Entities
Section titled “Entities”The Order aggregate shown above:
orders-checkout-domain-model.zdl
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}becomes a JPA data class, with @json fields mapped as JSON columns:
Order.kt
@Entity@Table(name = "checkout_order")@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)@org.jmolecules.ddd.annotation.AggregateRootdata class Order( @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @org.jmolecules.ddd.annotation.Identity var id: Long? = null, @Version var version: Int? = null, @NotNull @Column(name = "order_id", nullable = false, unique = true) var orderId: String? = null, @NotNull @Column(name = "status", nullable = false) @Convert(converter = OrderStatus.OrderStatusConverter::class) var status: OrderStatus = OrderStatus.CREATED,
/** Customer snapshot taken at checkout (there is no customers bounded context yet). */ @NotNull @Column(name = "customer_id", nullable = false) var customerId: String? = null, @NotNull @Size(max = 254) @Column(name = "customer_email", nullable = false, length = 254) var customerEmail: String? = null, @NotNull @Column(name = "payment_method_id", nullable = false) var paymentMethodId: String? = null, @NotNull @Size(min = 1) @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON) @Column(name = "items") var items: MutableList<OrderItem> = mutableListOf(), @NotNull @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON) @Column(name = "shipping_address") var shippingAddress: ShippingAddress? = null, @NotNull @Column(name = "total_amount", nullable = false) var totalAmount: BigDecimal? = null, @NotNull @Size(max = 3) @Column(name = "currency", nullable = false, length = 3) var currency: String? = null, @Column(name = "created_at") var createdAt: Instant? = null, @Column(name = "confirmed_at") var confirmedAt: Instant? = null, @Column(name = "cancelled_at") var cancelledAt: Instant? = null, @Column(name = "cancellation_reason") var cancellationReason: String? = null,) : Serializable {
companion object { private const val serialVersionUID = 1L }
override fun toString(): String { return this::class.java.name + "#" + id }
/* https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-with-jpa-and-hibernate/ */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Order) return false return id != null && id == other.id }
override fun hashCode(): Int { return javaClass.hashCode() }}In-process event listeners
Section titled “In-process event listeners”A command annotated with @listener:
orders-checkout-domain-model.zdl
@listener(zdl: PaymentsProcessingZdl, event: PaymentAuthorized) @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]becomes a Spring Modulith @ApplicationModuleListener:
PaymentsProcessingEventsListener.kt
/** * Internal domain event listeners for PaymentsProcessingZdl. * * This class is generated once and can be customized safely. */@Component@org.jmolecules.architecture.hexagonal.PrimaryAdapterclass PaymentsProcessingEventsListener(private val ordersCheckoutService: OrdersCheckoutService) {
private val mapper: PaymentsProcessingEventsListenerMapper = PaymentsProcessingEventsListenerMapper.INSTANCE
@ApplicationModuleListener fun onPaymentAuthorized(event: com.arcadiaeditions.payments.processing.domain.event.PaymentAuthorized) { ordersCheckoutService.confirmOrder(mapper.asConfirmOrderInput(event)) }}The last mile: behavior implemented against the rules
Section titled “The last mile: behavior implemented against the rules”The service methods are generated as TODOs and implemented afterwards, following the rules. confirmOrder in Kotlin:
OrdersCheckoutServiceImpl.kt: confirmOrder
override fun confirmOrder(input: ConfirmOrderInput): Order {
log.debug("Request confirmOrder: {}", input)
val order = orderRepository.findByOrderId(input.orderId) ?: throw NoSuchElementException("Order not found") // redelivery: an already CONFIRMED order does nothing if (order.status == OrderStatus.CONFIRMED) { return order } // CANCELLED: rejected without calling inventory if (order.status == OrderStatus.CANCELLED) { return reject(order, "ORDER_CANCELLED") } OrderTransitions.ensureCanConfirmOrder(order) val result = inventoryService.confirmStockReservation(ConfirmStockReservationInput(orderId = input.orderId)) if (result.outcome == ConfirmStockReservationOutcome.NOT_HELD) { return reject(order, "STOCK_NOT_HELD") } order.status = OrderStatus.CONFIRMED order.confirmedAt = Instant.now(clock) val saved = orderRepository.save(order) eventPublisher.onOrderConfirmed(eventsMapper.asOrderConfirmed(saved)) return saved }
private fun reject(order: Order, reason: String): Order { val event = eventsMapper.asOrderConfirmationRejected(order) event.reason = reason event.rejectedAt = Instant.now(clock) eventPublisher.onOrderConfirmationRejected(event) return order }The Kotlin modulith has one integration test per path of the flow (PlaceOrderFlowCompletedIntegrationTest, PlaceOrderFlowStockGoneIntegrationTest, PlaceOrderFlowDeclinedIntegrationTest, PlaceOrderFlowReservationExpiredIntegrationTest…):
PlaceOrderFlowStockGoneIntegrationTest.kt
/** * place-order-flow, path `stockGone` (place-order-flow.zfl:82-99, end 262-266): StartOrderCheckout for SKU-003 * (available 0) emits StockUnavailable and ends in StockUnavailableNotificationSent; no order, reservation or payment * (C-07 shape, A-05). Not @Transactional: the module listeners run after commit. */@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, // T-43: no replay, at startup, of incomplete publications another context or run left in event_publication properties = ["spring.modulith.events.republish-outstanding-events-on-restart=false"],)@ActiveProfiles("test")@DockerComposeInitializer.EnableDockerCompose@EnableScenarios@Import(TestClockConfiguration::class)// T-43: a fresh context per flow class (schema + data.sql reloaded, new async threads). Scenario captures events through// an InheritableThreadLocal, which async listener threads already created in a reused context never see.@DirtiesContext// T-43: no resubmitIncompletePublications tick: its first run, right after startup, resubmits this test's in-flight// publications and the listener runs twice (seen: two STOCK_UNAVAILABLE notifications for one order)@MockitoBean(types = [ExternalizationConfiguration::class])class PlaceOrderFlowStockGoneIntegrationTest {How to run
Section titled “How to run”Prerequisites: JDK 25, Maven 3.6+, Docker. Install the ZenWave CLI with JBang as explained in Getting Started.
git clone https://github.com/arcadia-editions/arcadia-editions-modulith-service-kotlin.git
cd arcadia-editions-modulith-service-kotlin
docker-compose up -d # local infrastructure (PostgreSQL)
mvn spring-boot:run
- SwaggerUI: http://localhost:8080/swagger-ui/index.html
- Actuator: http://localhost:8080/actuator
Tests:
mvn test # unit tests (*Test)
mvn verify # unit + integration tests (*IT, *IntegrationTest) and JaCoCo report
To regenerate after a model change, run the plugins in zenwave-scripts.zw, then mvn -DskipTests clean test-compile. Service implementations, listeners, mappers and tests are generated once and then belong to you: a normal run does not overwrite them, --force does.