Overview

7 Enforcing the architecture as executable specification

Architectural rules by themselves are easy to describe but hard to keep in place once a codebase grows. This chapter shows how to turn the intended hexagonal boundaries into executable tests with ArchUnit, so violations are detected automatically during the build instead of being discovered later by manual code review. Maven modules still do useful work by preventing illegal module-to-module imports at compile time, but ArchUnit fills the gaps by checking relationships that remain technically legal to the compiler, such as wrong constructor dependencies, misplaced annotations, broken naming conventions, and incorrect generic signatures.

The chapter builds this verification layer around a configurable setup so the same rules can be reused across projects. Package boundaries and allowed libraries are externalized in YAML, then injected into checker classes through Spring Boot. From there, the rules are organized by architectural role: inner layers use allowlists, adapters use denylists, and annotations are checked so each stereotype appears only where it belongs. Structural rules go further by ensuring ports are interfaces, commands and queries implement the right marker types, validation factories exist with the correct signatures, and use case interfaces carry the correct generic parameters. Custom predicates and conditions make it possible to express rules that the fluent DSL alone cannot capture.

The result is a complete test suite that acts like living architectural documentation. Each checker is wired into a thin Spring Boot test class that scans the relevant packages and delegates to ArchUnit, so the rules remain isolated, readable, and easy to run in CI or locally. The chapter also explains how to adopt these rules safely in an existing system using ArchUnit’s freeze mechanism, which records current violations and fails only on new ones until the backlog is cleaned up. In the end, the architecture becomes something the build can enforce continuously, keeping the code aligned with the intended design.

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.
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.
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.
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.
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.
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 if Maven modules already enforce architectural boundaries?ArchUnit complements Maven by enforcing rules that module boundaries cannot catch. Maven prevents wrong imports between modules at compile time, but ArchUnit checks class-level relationships inside the full classpath at test time, such as forbidden constructor dependencies, misplaced annotations, naming conventions, and incorrect generic types.
Why are ArchUnit tests placed in the spring-boot-assembly module?The assembly module sees all production modules on one classpath, so ArchUnit can analyze the entire application in one pass. It is also the module that already bootstraps Spring, which makes it a natural place to load configuration properties for the architectural rules.
What problem does externalized YAML configuration solve for architectural rules?It removes hardcoded package names and allowlists from rule code. The same ArchUnit rules can be reused across projects by changing YAML values instead of editing Java, making the checks portable and easier to maintain.
How do dependency rules differ for inner layers and adapters?Inner layers use allowlists: they declare what they may depend on. Adapters use a denylist: they declare what they must not depend on. This works because adapters may legitimately use many external frameworks, but they must never depend on the core application layers.
Why is the persistence adapter allowed to depend on domain types?Because repository implementations must implement repository interfaces declared in the domain. A persistence adapter like JpaArticleRepository needs to reference domain repository interfaces to fulfill its contract, so the dependency rule explicitly carves out that exception.
What annotation rules are enforced on commands, queries, ports, and handlers?Commands and queries are checked for forbidden stereotypes from other layers. Input ports must be annotated with @UseCase, output ports with @OutputPort, and handlers with @ApplicationService. These rules ensure each class has the correct architectural identity.
Why does the domain layer need a custom annotation condition?The domain layer allows a specific set of annotations, or none at all, which is more complex than a simple required-or-forbidden rule. A custom ArchCondition is needed to express “allowed annotations or no annotation” precisely.
What structural rules are enforced on commands and queries?Commands and queries must implement their marker interfaces, expose a public static validateThenCreate factory method that returns Either, and not have a public default constructor. These rules ensure objects are created in a valid state and through the intended API.
How are use case naming conventions enforced?A custom predicate identifies handlers that implement an interface annotated with @UseCase, and a custom condition checks that the handler name matches the pattern InterfaceName minus “UseCase” plus “Handler”. For example, PublishArticleUseCase must map to PublishArticleHandler.
What does the ArchUnit freeze mechanism do?It lets teams adopt architectural rules incrementally. Existing violations are stored as a baseline, and only new violations fail the build. As old problems are fixed, the stored violations shrink until the freeze wrapper can be removed and the rule enforced strictly.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free