9 Building WriteFlow: The complete implementation
WriteFlow is assembled here as a complete, runnable hexagon rather than as a set of isolated examples. The chapter revisits the domain, ports, handlers, adapters, composition root, and tests already introduced earlier, then snaps them together into one vertical slice that can create an article, publish it, read it back, and react to publication through event-driven follow-up work. The main lesson is not new code, but the way all the previously established pieces cooperate as a single system.
At the center sits an always-valid domain model: value objects guard raw data, the aggregate owns state transitions, and publication is modeled as a guarded behavior that records a domain event. The supporting contracts are kept cleanly separated: commands and queries carry primitives, input ports define use cases, output ports describe needs, and the repository bridges persistence in domain terms. The publish flow is especially important because one domain event is consumed in two different ways: once before commit to atomically record an integration event in the outbox, and once after commit to trigger a best-effort notification.
The outer layers complete the system without contaminating the core. A persistence adapter translates between aggregates and JPA rows, the outbox adapter stores integration-event intent in the same transaction as the article update, a fake notification adapter stands in for external delivery, and the REST controller turns HTTP requests into validated commands and queries. A composition root wires everything together by role, not by concrete class, and executable tests prove both the architecture and the behavior: dependencies point inward, forbidden calls such as reconstitution are constrained, and the end-to-end create-publish-get path works with the expected transactional guarantees.
Without an architectural structure, technical debt compounds exponentially. Hexagonal architecture keeps cost of change manageable by isolating change impact.
Publishing an article: one domain event, dispatched to two transactional listeners in two different phases. The before-commit listener writes the outbox row inside the publish transaction (atomic with the article); the after-commit listener attempts to notify subscribers only after the transaction commits. The handler that raised the event is unaware of either.
Creating an article using the WriteFlow API replies with a 201 Created when the request body is properly provided.
The new article has been persisted into the database using the data provided through the WriteFlow API call.
When publishing an article using the WriteFlow API, the successful response is a 204 No Content.
The side effect of the domain event ends up as a record in the corresponding table of the database.
Summary
- An always-valid aggregate, with a guarded reconstitution path: Article can only be created through validateThenCreate, which enforces every invariant; it can only be rehydrated through reconstitute, which trusts persisted data and raises no events. The split keeps the domain pure without making loading impossible, and a custom ArchUnit rule (not a visibility modifier) guarantees reconstitute is reached only from the persistence adapter.
- Either-only error handling, all the way out: Value objects, the entity, commands, queries, and output ports all return Either<Error, T>. Expected failures travel as left values along functional rails from the core to the controller, where a switch over the sealed Error hierarchy maps each one to an HTTP status with no default branch, so a new error variant cannot compile until someone decides its status. Exceptions are reserved for the genuinely exceptional, caught by a separate @ControllerAdvice.
- Ports that hide technology behind contracts. Every output port carries the OutputPort suffix and an @OutputPort stereotype marker; every adapter carries @Adapter; output port implementations are package-private, while event listener adapters are public framework-facing classes. The core depends on the interface, the composition root binds the implementation, and substituting one adapter for another—the fake notification for chapter 5's real email gateway, H2 for a production database—is an assembly-time decision that touches no core code.
- The transactional outbox, recorded atomically with the business change. Publishing an article and recording its integration event happen in one transaction, because the BEFORE_COMMIT listener writes the outbox row inside the publish transaction and a failed write aborts the whole publication. The published-article fact lives in three representations—domain event, integration event, outbox row—each serving a different audience and changing for a different reason.
- Stereotype-driven assembly. The composition root wires beans by architectural role (adding @ApplicationService, @Adapter, and @DomainService to Spring’s default component-scanning rules) rather than by name, which keeps framework annotations out of the inner layers and lets the command and query buses derive their routing tables from the handlers' generic types. Adding a use case requires no edit to the composition root.
- Architecture and behavior, both verified on every build. WriteFlow reuses the chapter 7 checker library through ArchTests.in(...), extends it with one project-specific rule, and applies the chapter 8 testing recipes by role. mvn clean verify is green only when the structure is provably hexagonal, and the behavior is provably correct.
FAQ
What is the main goal of Chapter 9 in WriteFlow?
The chapter assembles the entire application end to end, from the domain core through ports, handlers, adapters, composition root, and verification. It shows how the pieces built in earlier chapters fit together into one runnable hexagonal application.
What two paths does WriteFlow implement in this chapter?
WriteFlow implements a command path and a query path. The command path publishes an article, and the query path reads an article back.
Why are value objects used for article fields like title and IDs?
Value objects make the model always valid by ensuring each field is constructed only when its rules are satisfied. For example, a title must be non-blank and at most 500 characters, and an article ID must be a valid UUID.
What is the difference between validateThenCreate and reconstitute on the Article aggregate?
validateThenCreate is used to create a new article and enforces all creation-time invariants, starting the article in DRAFT. reconstitute is used to rebuild a persisted article without revalidating it, trusting the stored state as ground truth.
Why does the Article aggregate raise an ArticlePublished event?
The aggregate raises ArticlePublished because publishing is a fact other parts of the system care about. The event is stored as data inside the aggregate and later dispatched by the application layer.
Why are commands and queries designed to carry primitives instead of domain types?
Commands and queries carry primitives so the input-ports module does not depend on the domain module. The handler reconstructs domain objects later, preserving boundary discipline and keeping dependencies pointing inward.
What is the role of the handlers in WriteFlow?
Handlers orchestrate use cases: they parse primitive inputs, invoke the domain, call output ports, and return results. They do not contain business rules; those remain in the domain model.
Why does WriteFlow use two different transactional listeners for the same domain event?
The before-commit listener records an integration event in the outbox atomically with the article publication, while the after-commit listener notifies subscribers only after the publication is durable. This demonstrates two different durability guarantees for the same event.
Why is the persistence model separate from the domain aggregate?
The JPA entity is separate because persistence needs mutable, framework-friendly structures, while the domain aggregate should stay pure and protected by its invariants. Separating them keeps JPA concerns out of the domain.
How does Chapter 9 verify that the hexagon is correctly assembled?
It uses ArchUnit architecture tests to prove dependencies point inward and that special rules, like restricted access to reconstitute, are enforced. It also uses behavioral tests to confirm that the domain, handlers, adapters, and controller all behave as intended.
Clean Applications with Hexagonal Architecture ebook for free