liveBook · Manning

Chapter 9: Building WriteFlow: The complete implementation

What you will learn in chapter 9 of Clean Applications with Hexagonal Architecture

The introduction explains how WriteFlow’s previously built parts will form a runnable application and why two consumers of one domain event run in different transaction phases.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction explains how WriteFlow’s previously built parts will form a runnable application and why two consumers of one domain event run in different transaction phases.

Key terms: vertical slice, composition root, listeners, controller wiring, ArticlePublished, domain event, integration event, outbox, before commit, after commit

9.1 What we are building

This section frames article publishing and reading as two small operations that exercise WriteFlow’s complete hexagon, and identifies when the publish event’s two consumers run.

Key terms: command path, query path, full hexagon, outbox writer, subscriber notification, publish transaction, before commit, after commit

9.2 The domain core

This section places WriteFlow’s article rules in a framework-independent domain core that the rest of the application serves.

Key terms: domain core, Article aggregate, business invariants, innermost ring

9.2.1 Value objects: The smallest always-valid things

This section shows how WriteFlow makes article fields always-valid value objects using private constructors, Either-returning factories, and shared validation helpers.

Key terms: value object, private constructor, validateThenCreate, Either<Error, VO>, Error.ValidationErrors, ArticleId, Title, chain, List, shared-kernel

9.2.2 The status: A two-state lifecycle

This section defines WriteFlow’s two article states and separates naming those states from governing transitions between them.

Key terms: ArticleStatus, draft, published, aggregate, enum

9.2.3 The Article aggregate: Creation, reconstitution, and behaviour

This section explains how the Article aggregate controls creation, restoration from persistence, publishing, and the domain events publishing produces.

Key terms: aggregate root, identity, state transition, validateThenCreate, reconstitute, creation-time invariant, DRAFT, ArticleStatus, persistence mapper, persistence adapter

9.2.4 The domain event: A primitive-typed, cross-boundary contract

This section explains why ArticlePublished is a primitive-typed event in WriteFlow’s shared kernel rather than a domain-module type.

Key terms: ArticlePublished, shared kernel, domain event, primitives, domain value objects

9.2.5 What the domain guarantees

This section summarizes WriteFlow’s domain guarantees and draws out design principles for keeping domain models valid and independent of infrastructure.

Key terms: Article, ArticlePublished, popDomainEvents, reconstitute, inside-out, domain core, aggregate, value object, guarded public factory, raw primitive

9.3 The ports

This section defines WriteFlow’s input and output ports as implementation-free contracts around the handlers and sealed domain core.

Key terms: input ports, output ports, use-case interface, command, query, adapter

9.3.1 Commands and queries carry primitives, not domain types

This section defines commands and queries as self-validating, primitive-carrying messages that keep the input-ports module independent of the domain.

Key terms: primitives, input-ports module, domain (value) objects, dependency arrow, validated message, validateThenCreate, Either, value-object factory, invariants, command

9.3.2 Input ports: The use cases the application offers

This section defines WriteFlow’s input ports as thin use-case contracts that separate messages and callers from handler implementations.

Key terms: input ports, use-case interface, Architecture Kernel’s handler types, handler, dependency-inversion seam, notify subscribers, record an integration event, commanded operations, assembly detail

9.3.3 The read-side DTO

This section explains why query results use a flat ArticleDTO instead of exposing the Article aggregate.

Key terms: ArticleDTO, Article, always-valid rule, String, ArticleStatus, domain entity, application boundary, publish(...), popDomainEvents(), Void

9.3.4 Output ports: What the application needs from the world

Defines the output-port contracts WriteFlow uses for event dispatch, durable integration-event relay, notifications, and persistence while keeping the application independent of adapter technology.

Key terms: output ports, OutputPort suffix, @OutputPort, adapter, DomainEventPublisherOutputPort, List<DomainEvent>, Article.popDomainEvents(), shared-kernel DomainEvent, IntegrationEventPublisherOutputPort, ArticlePublished

9.3.5 The contracts are complete

This section completes WriteFlow’s behavior-free contracts and explains how their dependency direction keeps the application boundary clean.

Key terms: contracts, input ports, output ports, read-side DTO, handlers, dependency direction, input port, output port, commands, queries

9.4 The handlers

This section establishes how WriteFlow handlers connect use-case ports to the domain and adapters, and explains the conventions that keep them encapsulated and transactional.

Key terms: handler, application service, use-case input port, output ports, Either, @ApplicationService, package-private, use-case interface, @Transactional, Either.left

9.4.1 Creating a draft: The simplest handler

The create-article handler illustrates parse-then-drive: turn a primitive command into value objects, assemble a draft Article, and persist it, returning the first failure if a step fails.

Key terms: parse-then-drive, primitive command, value objects, Article.validateThenCreate, DRAFT, left, events, creation operations, use cases

9.4.2 Publishing: The handler at the heart of the chapter

This section traces how the publish handler delegates publication to the Article aggregate, saves it, and dispatches its domain events through an output port.

Key terms: publish handler, Article aggregate, ArticlePublished, Either<Error, Void>, flatMap, popDomainEvents(), save, DomainEventPublisherOutputPort, ApplicationEventPublisher, Right

9.4.3 One event, two phases: The listeners

This section shows how two listeners react to an article publication at different transaction phases, making the outbox write atomic while treating subscriber notification as a best-effort post-commit effect.

Key terms: ArticlePublished, event-listener adapters, CommandBus, RecordIntegrationEventHandler, NotifySubscribersHandler, output ports, BEFORE_COMMIT, outbox, Either.left, peekLeft

9.4.4 Reading: The query handler

This section shows how WriteFlow reads an article through a simple query handler without exposing the aggregate or triggering write-side work.

Key terms: GetArticleByIdHandler, DTO, aggregate, popDomainEvents

9.4.5 The two paths at runtime

This section traces WriteFlow’s read and publish paths, explains the transaction timing of publish-event consumers, and identifies what the completed application core still cannot do without adapters.

Key terms: GetArticleByIdQuery, query bus, GetArticleByIdHandler, findById, ArticleDTO, domain event, outbox write, AFTER_COMMIT, subscriber notification, save and dispatch order

9.5 Adapters: Wiring the core to the outside world

This section explains how WriteFlow’s adapters connect the completed core to external technology while keeping dependencies pointed inward.

Key terms: driven adapter, driving adapter, output port, input port, @Adapter, ArchUnit, package-private, ArticlePersistenceMapper, ApiMapper

9.5.1 The persistence adapter

This section shows how WriteFlow’s persistence adapter translates between domain contracts and JPA while protecting aggregate invariants and accounting for transaction behavior.

Key terms: ArticleRepository, JpaArticle, Article aggregate, Spring Data, validateThenCreate, reconstitute, toDomainEntity, ReconstitutionAccessArchitectureTest, DataAccessException, Either left

9.5.2 The transactional outbox

Explains how WriteFlow records a pending integration event atomically with article publication, while keeping domain, external, and storage representations separate.

Key terms: dual-write problem, transactional outbox, BEFORE_COMMIT, outbox row, ArticlePublished, ArticlePublishedIntegrationEvent, OutboxMessage, domain event, integration event, Left

9.5.3 The event bridge and the notification fake

This section contrasts a real transactional event bridge with a fake notification adapter to show how ports support substitution and how prototypes can focus implementation effort.

Key terms: DomainEventPublisherOutputPort, SpringDomainEventPublisher, Spring application event, BEFORE_COMMIT/AFTER_COMMIT, NotificationOutputPort, EmailNotificationAdapter, Liskov-substitutability, assembly-time decision, outbox, publish path

9.5.4 The REST driving adapter

The section shows how WriteFlow’s REST adapter translates HTTP requests into core invocations and maps their outcomes back to HTTP without putting business logic in the controller.

Key terms: request records, always-valid, validateThenCreate, driving adapter, input port, command bus, query bus, mapLeft, fold, server-generated id

9.5.5 The edges are built, nothing is connected

This section explains why WriteFlow’s completed adapters do not yet make a running application, and how translation and port design keep the core separate from infrastructure.

Key terms: composition root, ports, adapters, command and query buses, adapter layer, types, errors, optionality, Either left, NotFound

9.6 Assembly: The composition root

This section explains why WriteFlow needs a composition root to connect its independent modules without breaking hexagonal boundaries.

Key terms: composition root, spring-boot-assembly module, hexagonal architecture

9.6.1 The bootstrap class

WriteFlow's minimal Spring Boot entry point lets base-package scanning and auto-configuration assemble the application's beans and JPA infrastructure without manual setup.

Key terms: @SpringBootApplication, base-package scan, JPA auto-configuration, composition root

9.6.2 Wiring beans by stereotype, not by name

WriteFlow’s composition root discovers beans by architectural role while ArchUnit, not component scanning, enforces the boundaries around those roles.

Key terms: component scan, Architecture Kernel stereotypes, @ApplicationService, @Adapter, @DomainService, Spring’s default component filters, ArchUnit rules, inner layers, framework coupling, architectural stereotypes

9.6.3 Standing up the buses and registering handlers

This section shows how the composition root creates command and query buses that discover typed handlers automatically, and why their configuration is kept separate from component scanning.

Key terms: CommandBus, QueryBus, Registry, ApplicationContext, CommandHandler, QueryHandler, CommandQueryBusAssembler, ApplicationAssembler, composition root, component-scan policy

9.6.4 Profile and runtime configuration

This section places runtime settings outside Java code and explains the conditions and limits of replacing WriteFlow’s H2 database.

Key terms: application.yaml, transaction manager, HTTP settings, H2, persistence adapter, repository port’s contract

9.6.5 The application is whole

The section shows the assembled WriteFlow application running, uses its API and database consoles to observe the publish path, and explains the boundaries that the composition root must preserve.

Key terms: bootstrap class, stereotype-filtered scan, bus assemblers, output ports, H2, Swagger UI, Springdoc, H2 web console, 201 Created, DRAFT

9.7 Verification: Proving the hexagon holds

This section explains why WriteFlow needs both architectural and behavioral tests to verify that its assembled hexagon has the right structure and works correctly.

Key terms: architectural tests, behavioral tests, composition root, dependency rule

9.7.1 Reusing the chapter 7 checker library

This section shows how WriteFlow reuses the chapter 7 ArchUnit checker library to verify its architectural roles without rewriting the rules.

Key terms: ArchUnit, archunit-hexagonal, @AnalyzeClasses, ArchTests.in(...), HexagonalArchitectureConfig, AdaptersArchitectureTest, AdapterChecker, driven and driving adapter

9.7.2 Extending the library with a project-specific rule

The section shows how WriteFlow adds a project-specific ArchUnit rule to its reusable architecture checks to restrict access to Article.reconstitute.

Key terms: Article.reconstitute, persistence-adapter package, architecture rule, validateThenCreate, publish state machine, ArchUnit, ClassFileImporter, ArchRuleDefinition, ArchTests.in(...), DO_NOT_INCLUDE_TESTS

9.7.3 Behavioral tests: Applying the chapter 8 recipes

This section applies behavioral test recipes to each WriteFlow component and explains why behavioral and architecture tests are both needed.

Key terms: architecture tests, behavioral tests, ArchUnit, ArticleTest, no-mocks recipe, ArticlePublished, reconstitute, Mockito-with-BDD recipe, PublishArticleHandlerTest, never()

9.7.4 The whole gate

The section shows how one build verifies both WriteFlow’s architecture and behavior, then explains how its boundaries help a larger system absorb change.

Key terms: mvn clean verify, architecture tests, unit tests, executable specification, ArchUnit rules, driving adapter, driven adapter, output port, composition root, use-case port

9.8 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 8: Testing the hexagon with behavioral verification Chapter 10: When hexagons talk: Integration modes and the external architecture →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.