7 Enforcing the architecture as executable specification
Chapter 7 shows how to turn hexagonal architecture from a set of guidelines into an executable specification. Maven modules already prevent obvious cross-module mistakes at compile time, but they cannot catch subtler problems that still compile, such as direct adapter references, misplaced stereotypes, or weak naming conventions. ArchUnit fills that gap by inspecting compiled classes during tests and failing the build whenever code violates the intended structure. In this way, architectural intent becomes part of the CI pipeline rather than something developers are expected to remember informally.
The chapter then builds a reusable testing foundation around externalized configuration. Package boundaries, allowed dependencies, and architectural layers are defined in YAML and injected into the rule classes, making the checks portable across projects and easy to update when the architecture changes. From there, it implements dependency rules for each layer, using allowlists for inner layers and denylists for adapters, while making room for legitimate exceptions such as repository implementations. It also adds annotation rules so that classes carry the right stereotypes in the right places, with custom conditions where the built-in fluent API is not expressive enough.
Finally, the chapter extends enforcement beyond dependencies and annotations to structural shape and naming. It verifies that ports are interfaces, commands and queries implement the correct marker interfaces, creation happens only through validated factory methods, and use-case handlers follow predictable naming patterns. All of these rules are wired into thin Spring Boot test classes that scan the relevant packages and delegate to the checkers. To make adoption practical in existing codebases, the freeze mechanism is used to baseline current violations and block only new ones, gradually shrinking technical debt until the rules can be enforced strictly.
ArchUnit tests surround the production architecture as a test-time verification layer. They act as executable documentation of the intended boundaries and help prevent architectural erosion.
The assembly module is the only component that sees everything and depends on all others.
Dependency rule strategy. Inner layers define what they may depend on (allowlist). Adapters define what they must not depend on (denylist). Repository implementations are the sole exception—they must reference domain entities to implement their contract.
Structural rule coverage by layer. Commands and queries carry the most structural constraints (five rules each). Input ports enforce interface shape and generic types. Other layers rely primarily on dependency and annotation rules.
Test execution structure. Each test class wires a specific checker to its target packages. The assembly module provides the classpath visibility that makes cross-module analysis possible. All checkers read their configuration from the same YAML properties.
Summary
- Maven modules enforce dependency direction at compile time—preventing wrong imports. ArchUnit enforces architectural relationships at test time—preventing wrong coupling, wrong stereotypes, and wrong naming within the classpath.
- Externalized YAML configuration makes rules portable across projects. Package names and allowed dependencies live in configuration, not in rule source code.
- Dependency rules use allowlists for inner layers (shared kernel, domain, handlers) and a denylist for adapters. Repository implementations are the sole exception to the adapter denylist.
- Annotation rules enforce both forbidden stereotypes (no @ApplicationService on a command) and required stereotypes (@UseCase on every input port, @OutputPort on every output port, @ApplicationService on every handler).
- Structural rules enforce the shape of commands, queries, and ports: marker interface implementation, validateThenCreate factory methods returning Either<Error, T>, no public default constructors, correct generic type arguments on use case interfaces.
- Naming convention rules guarantee that every handler implementing a @UseCase interface follows the [VerbNoun]Handler pattern derived from the interface name.
- Custom ArchCondition and DescribedPredicate implementations extend the fluent DSL when built-in methods are insufficient—covering method signature inspection, constructor analysis, and generic type position validation.
- All rules execute in the spring-boot-assembly module, where the full classpath is visible. Each test class wires a checker to its target packages through a minimal Spring Boot test context.
- The freeze mechanism enables incremental adoption: existing violations are recorded and tolerated while new violations fail the build immediately. The violation store shrinks as the team fixes legacy issues.
FAQ
Why use ArchUnit tests if Maven modules already enforce dependencies?
Maven modules prevent wrong imports across artifacts at compile time, but they cannot detect architectural violations that are legal on the classpath, such as a handler depending directly on an adapter, a wrong annotation on a class, or an incorrect naming convention. ArchUnit fills that gap by checking class-level structure at test time.
Why are ArchUnit tests placed in the spring-boot-assembly module?
The assembly module depends on all other modules, so it has the full classpath needed to inspect every class in the application in one pass. It is also the place where Spring Boot bootstrap and configuration properties are already available for loading rule settings.
What problem does externalized YAML configuration solve for architecture rules?
It makes package boundaries and allowed dependencies portable. Instead of hardcoding package names in Java rules, the YAML file defines layer locations and allowed libraries, so the same checker code can be reused across projects with different package structures.
Why do inner layers use allowlists while adapters use denylists?
Inner layers have a limited, well-defined set of allowed dependencies, so an allowlist is clear and maintainable. Adapters may legitimately depend on many external frameworks, so it is easier to specify the small set of core packages they must never depend on.
What does the shared kernel dependency rule enforce?
It enforces that classes in the shared kernel depend only on approved libraries such as the JDK, Vavr, Lombok, Apache Commons, and the shared kernel itself. It blocks any dependency on application code, domain code, or frameworks.
Why do commands and queries need annotation rules?
Annotation rules ensure each class carries the stereotype that matches its architectural role. For example, commands must not be annotated like handlers or ports, and input ports must be marked with @UseCase so the architecture remains explicit and unambiguous.
How does ArchUnit enforce that ports are interfaces?
It checks that classes in the input-port and output-port packages are interfaces, not concrete classes. This preserves the contract nature of ports and prevents implementations from being mixed into the API boundary.
Why is a custom ArchCondition needed for validateThenCreate?
Because the rule is more specific than simple type checking: the method must be public, static, named exactly validateThenCreate, return an Either, and use the enclosing class as the second type argument. That combination requires custom bytecode inspection logic.
How does the handler naming convention rule work?
It looks for classes that implement an interface annotated with @UseCase, derives the expected name by replacing UseCase with Handler, and fails the test if the implementation class does not match that pattern. This keeps handler names predictable and easy to find.
What is the purpose of the freeze mechanism in ArchUnit?
The freeze mechanism lets a team adopt architectural rules incrementally. It records existing violations on first run and fails only on new violations afterward, allowing legacy debt to remain visible and controlled while preventing further drift.
Clean Applications with Hexagonal Architecture ebook for free