Skip to content

Arcadia Editions Modulith: Spring Boot Java

Section titled “Arcadia Editions Modulith: Spring Boot Java”

The six Arcadia Editions bounded contexts (orders checkout, catalog inventory, catalog products, payments processing, fulfillment shipping, notifications consumer) as one Java + Spring Boot modular monolith: one Spring Modulith module per context, in-process events with a transactional outbox.

  • The structure is generated from the ZDL models with ZenWave SDK.
  • The behavior of the place-order flow was implemented with zenwave-sdd: models reviewed by a human in the loop (HITL), implementation done by coding agents away from keyboard (AFK).

Source code: arcadia-editions-modulith-service-java. Models: arcadia-editions-modulith-api.

AreaTechnology
LanguageJava 25
FrameworkSpring Boot 4.2.x
Modular monolithSpring Modulith 2.2.x + JDBC event publication registry (no broker)
PersistenceSpring Data JPA + PostgreSQL
DDD / ArchitecturejMolecules + ArchUnit
Code generationZenWave SDK 2.8.x, openapi-generator-maven-plugin

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 not in the service repository. They live in arcadia-editions-modulith-api, one ZDL per bounded context, and are released as a Maven artifact (service-all) that zenwave-scripts.zw imports.

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

Its rules and @invariant: the last-mile spec

Section titled “Its rules and @invariant: the last-mile spec”

Structure is what the generator can build: entities, commands, events, state transitions, listeners. Behavior is the last mile. ZDL captures it in rules blocks, written in natural language. An @invariant must always hold for the aggregate. A plain rule is a policy of the service. These sentences are the spec a coding agent implements and tests 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

Service-level rules describe how the commands collaborate with other modules:

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

Navigate to source

The same pattern in Catalog Inventory, aggregate first and then its rules:

catalog-inventory-domain-model.zdl: StockReservation aggregate and rules

Navigate to source

catalog-inventory-domain-model.zdl: service rules

Navigate to source

The rules of the whole flow, across contexts, are in place-order-flow.zfl.

orders-checkout-domain-model.zdl

Navigate to source

catalog-inventory-domain-model.zdl

Navigate to source

payments-processing-domain-model.zdl

Navigate to source

fulfillment-shipping-domain-model.zdl

Navigate to source

notifications-consumer-domain-model.zdl

Navigate to source

catalog-products-domain-model.zdl

Navigate to source

Each model’s config sets the module’s moduleBasePackage and layout (this modulith mixes layouts on purpose), and its apis block declares the other modules it talks to as zdl clients:

orders-checkout-domain-model.zdl: config and apis

Navigate to source

zenwave-scripts.zw imports the released models and runs BackendApplicationDefaultPlugin once per module, then OpenAPIControllersPlugin and SpringWebTestClientPlugin for the Orders Checkout REST API. The shared common packages keep base classes in one place for all modules.

zenwave-scripts.zw
@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
plugins {
/** Generates a Backend Application from the ZDL model. (Headless Core) */
BackendApplicationDefaultPlugin {
zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-inventory-domain-model.zdl"
}
BackendApplicationDefaultPlugin {
zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/catalog-products-domain-model.zdl"
}
BackendApplicationDefaultPlugin {
zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/fulfillment-shipping-domain-model.zdl"
}
BackendApplicationDefaultPlugin {
zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/notifications-consumer-domain-model.zdl"
}
BackendApplicationDefaultPlugin {
zdlFile "classpath:/com/arcadiaeditions/modulith/application/arcadia-editions-modulith/orders-checkout-domain-model.zdl"
}
BackendApplicationDefaultPlugin {
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 {
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 {
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
}
}
}

Navigate to source

Open the file in the IDE with the ZenWave plugin and use the play button next to each plugin. Hovering the button shows the equivalent jbang zw -p <Plugin> ... command line.

Each ZDL service becomes an inbound port. Javadoc and the events of each command come from the model:

Given this service in the ZDL:

orders-checkout-domain-model.zdl

Navigate to source

BackendApplicationDefaultPlugin generates this inbound port, exposed as a Spring Modulith named interface:

OrdersCheckoutService.java
/**
* Inbound Service Port for managing [Order].
*/
@org.springframework.modulith.NamedInterface("OrdersCheckoutService")
@org.jspecify.annotations.NullMarked
@org.jmolecules.architecture.hexagonal.PrimaryPort
public interface OrdersCheckoutService {
/**
* Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A).
*
* With Events: [[OrderCreated, StockUnavailable]].
*
*/
public Order startOrderCheckout(StartOrderCheckoutInput input);
/**
* 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.
*
* With Events: [[OrderConfirmed, OrderConfirmationRejected]].
*
*/
public Order confirmOrder(ConfirmOrderInput input);
/**
* No-op, no event, on CANCELLED (redelivered StockReleased).
*
* With Events: [OrderCancelled].
*
*/
public Order cancelOrder(CancelOrderInput input);

Navigate to source

State transitions from @lifecycle and @transition

Section titled “State transitions from @lifecycle and @transition”

Commands declare which states they move the aggregate between:

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]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */
@listener(zdl: CatalogInventoryZdl, event: StockReleased)
@transition(from: [CREATED, CONFIRMED], to: CANCELLED)
cancelOrder(CancelOrderInput) Order withEvents OrderCancelled

Navigate to source

and the generator writes the guards:

OrderTransitions.java
public final class OrderTransitions {
private OrderTransitions() {}
public static void ensureCanConfirmOrder(Order entity) {
require("confirmOrder", entity, OrderStatus.CREATED);
}
public static void ensureCanCancelOrder(Order entity) {
require("cancelOrder", entity, OrderStatus.CREATED, OrderStatus.CONFIRMED);
}
private static void require(String command, Order entity, OrderStatus... allowed) {
var current = entity.getStatus();
for (var state : allowed) {
if (current != null && current == state) {
return;
}
}
throw new InvalidStateTransitionException(
entity.getClass().getSimpleName(), entity.getId(), null, command, current, Arrays.asList(allowed));
}

Navigate to source

A command annotated with @listener reacts to an event of another module:

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

which becomes a Spring Modulith @ApplicationModuleListener calling the inbound port:

PaymentsProcessingEventsListener.java
/**
* Internal domain event listeners for PaymentsProcessingZdl.
*
* This class is generated once and can be customized safely.
*/
@Component
@org.jmolecules.architecture.hexagonal.PrimaryAdapter
public class PaymentsProcessingEventsListener {
private final OrdersCheckoutService ordersCheckoutService;
private final PaymentsProcessingEventsListenerMapper mapper = PaymentsProcessingEventsListenerMapper.INSTANCE;
public PaymentsProcessingEventsListener(OrdersCheckoutService ordersCheckoutService) {
this.ordersCheckoutService = ordersCheckoutService;
}
@ApplicationModuleListener
public void onPaymentAuthorized(com.arcadiaeditions.payments.processing.domain.event.PaymentAuthorized event) {
ordersCheckoutService.confirmOrder(mapper.asConfirmOrderInput(event));
}
}

Navigate to source

Events are published through Spring’s ApplicationEventPublisher. With the Spring Modulith JDBC event publication registry, listeners run after the publishing transaction commits:

DefaultEventPublisher.java

Navigate to source

The last mile: behavior implemented against the rules

Section titled “The last mile: behavior implemented against the rules”

The generator leaves service methods as TODOs. Here is confirmOrder after the AFK implementation: a no-op on redelivery, a rejection on CANCELLED or NOT_HELD stock, as the rules confirmOnlyWithHeldStock and rejectedConfirmationVoids say.

OrdersCheckoutServiceImpl.java: confirmOrder
public Order confirmOrder(ConfirmOrderInput input) {
log.debug("Request confirmOrder: {}", input);
var existing = orderRepository.findByOrderId(input.getOrderId()).orElseThrow();
if (existing.getStatus() == OrderStatus.CONFIRMED) {
log.debug("confirmOrder redelivery, order already CONFIRMED: {}", input.getOrderId());
return existing;
}
if (existing.getStatus() == OrderStatus.CANCELLED) {
reject(existing, "ORDER_CANCELLED");
return existing;
}
OrderTransitions.ensureCanConfirmOrder(existing);
var stock = inventoryService.confirmStockReservation(
new ConfirmStockReservationInput().setOrderId(existing.getOrderId()));
if (stock.getOutcome() == ConfirmStockReservationOutcome.NOT_HELD) {
reject(existing, "STOCK_NOT_HELD");
return existing;
}
existing.setStatus(OrderStatus.CONFIRMED);
existing.setConfirmedAt(clock.instant());
var order = orderRepository.save(existing);
// emit events
var orderConfirmed = eventsMapper.asOrderConfirmed(order);
eventPublisher.onOrderConfirmed(orderConfirmed);
return order;
}
private void reject(Order order, String reason) {
var rejected = eventsMapper.asOrderConfirmationRejected(order);
rejected.setReason(reason);
rejected.setRejectedAt(clock.instant());
eventPublisher.onOrderConfirmationRejected(rejected);
}

Navigate to source

The flow is covered end to end by PlaceOrderFlowTest, one scenario per outcome of the flow:

PlaceOrderFlowTest.java

Navigate to source

Prerequisites: Java 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-java.git
cd arcadia-editions-modulith-service-java
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.