9 Building WriteFlow: The complete implementation
The chapter pulls together the entire WriteFlow application as one continuous vertical slice, not by introducing new patterns, but by connecting the ones already built earlier. It shows how the domain core, ports, handlers, adapters, and composition root fit together into a runnable system that can create a draft, publish an article, and read it back. The emphasis is on assembling inside-out: starting with the always-valid domain model, then adding contracts, orchestration, infrastructure, and finally the wiring that makes the whole thing executable.
At the center is a small but complete domain: validated value objects, a two-state article lifecycle, an aggregate that enforces publish rules, and a domain event that is raised when publication succeeds. The chapter also stresses boundary discipline: commands and queries carry primitives, not domain types; use-case interfaces stay thin; handlers parse input back into the domain and orchestrate behavior without owning business rules. One domain event is intentionally consumed in two ways, with different transaction guarantees: one listener records an outbox entry before commit so the database change and integration intent stay atomic, while another notifies subscribers after commit as a best-effort side effect.
The outer layers then translate that model into real technology. A separate persistence model keeps JPA concerns out of the domain, the outbox stores serialized integration events, a fake notification adapter stands in for external delivery, and the REST adapter turns HTTP requests into validated commands and queries. The final part of the chapter proves the architecture with executable checks: ArchUnit rules enforce inward-only dependencies and a project-specific rule protects reconstitution, while behavioral tests confirm that each layer does its job. The result is a complete example of hexagonal architecture that is not just diagrammed, but assembled, run, and verified.
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 complete WriteFlow application into one runnable whole, connecting the domain core, ports, handlers, adapters, composition root, and verification rules without introducing new architectural patterns.Why does the chapter build both a command path and a query path?
Because publish/write and read/query cover the two fundamental shapes of the architecture. Building both shows how the hexagon handles state-changing and read-only use cases end to end.Why are value objects used for fields like ArticleId, Title, Content, and AuthorId?
They make each field always valid by construction. Instead of passing raw strings around, the domain uses value objects so invalid data cannot enter the core unnoticed.What is the difference between Article.validateThenCreate and Article.reconstitute?
validateThenCreate creates a brand-new article and enforces all creation rules, while reconstitute rebuilds an already persisted article without revalidating it.Why is ArticlePublished kept in the shared kernel instead of the domain module?
So multiple layers can use the event contract without depending on the domain module. It is expressed with primitive types to avoid dragging domain types into listeners, publishers, or adapters.Why do commands and queries carry primitives instead of domain objects?
To keep the input-ports module independent from the domain. The handler is responsible for converting primitives into domain value objects when the request crosses the application boundary.What is the role of the handlers in this chapter?
Handlers orchestrate the application flow: they parse primitives, invoke the domain, call ports, and returnEither. They do not contain business rules; those stay in the aggregate.Why does publish save the article before dispatching domain events?
So no event escapes for a publication that failed to persist. Saving first, then dispatching, ensures the event flow only continues for committed state.Why are there two listeners for ArticlePublished, and why do they use different transaction phases?
One listener runsBEFORE_COMMIT to record an outbox row atomically with the article update. The other runs AFTER_COMMIT to notify subscribers as a best-effort side effect after the transaction is durable.How does the chapter verify that the architecture is correct?
It uses ArchUnit tests to prove dependency direction and custom rules like restrictingreconstitute to the persistence package, plus behavioral tests to prove aggregates, handlers, adapters, and controllers all work correctly.
Clean Applications with Hexagonal Architecture ebook for free