Skip to content

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.

AreaTechnology
LanguageKotlin 2.5.x (kapt) on JDK 25
FrameworkSpring Boot 4.0.x
Modular monolithSpring Modulith 2.0.x + JDBC event publication registry (no broker)
PersistenceSpring Data JPA + PostgreSQL
MappingMapStruct (via kapt)
FormattingSpotless + ktlint

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.

Arcadia Editions modulith: modules, bounded contexts and how they talk

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.

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
}

Navigate to source

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

Navigate to source

orders-checkout-domain-model.zdl: service and rules

Navigate to source

Compared to the Java modulith, the script imports the kotlin-backend-application customization and sets Kotlin templates on each plugin:

zenwave-scripts.zw

Navigate to source

zenwave-scripts.zw: imports
@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")

Navigate to source

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

Navigate to source

zenwave-scripts.zw: controllers and API tests

Navigate to source

The Order aggregate shown above:

orders-checkout-domain-model.zdl

Navigate to source

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.AggregateRoot
data 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()
}
}

Navigate to source

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]

Navigate to source

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.PrimaryAdapter
class 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))
}
}

Navigate to source

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
}

Navigate to source

The Kotlin modulith has one integration test per path of the flow (PlaceOrderFlowCompletedIntegrationTest, PlaceOrderFlowStockGoneIntegrationTest, PlaceOrderFlowDeclinedIntegrationTest, PlaceOrderFlowReservationExpiredIntegrationTest…):

PlaceOrderFlowStockGoneIntegrationTest.kt

Navigate to source

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

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.