Spring Modulith Module ArchUnit
A utility library for enforcing architectural standards within Spring Modulith modules using ArchUnit, with a focus on hexagonal architecture.
Table of Contents
- Overview
- Project Structure
- Getting Started
- Rule Groups
- Default Rules for Hexagonal Architecture
- Implementation Details
Overview
Spring Modulith is a powerful framework for managing module dependencies and provides integration with jMolecules to enforce modular boundaries. However, there are cases, when additional rules and validations are required to maintain internal structure and compliance with architectural standards, such as the hexagonal architecture.
The Spring Modulith Module ArchUnit library is purpose-built to address this gap by offering:
- A set of predefined ArchUnit rules for hexagonal architecture.
- Flexible customization for hexagonal or other architectures.
- Seamless integration with Spring Modulith’s module verification capabilities.
Design Background
The library enforces the module boundaries of a modular monolith whose modules follow hexagonal architecture. Spring Modulith checks the dependencies between modules, and the rules of this library check the ports, adapters and services inside each module, so that a module keeps its internals hidden behind its ports. The author develops this idea of encapsulation in his book Laminar Software Design: Foundations of High-Quality Code.
Project Structure
The project consists of two libraries:
- spring-modulith-module-archunit
Provides implementations of ArchUnit rules and support for Spring Modulith module verification.
- spring-modulith-module-archunit-starter
A Spring Boot starter that pre-configures ArchUnit rules and exposes services for architecture validation in tests.
Getting Started
Installation
Add the following dependencies to your project. These libraries require Java 17+ and Spring Boot 4+.
Using Gradle:
dependencies {
testImplementation("dev.clutcher.modulith:spring-modulith-module-archunit:2.1.0")
testImplementation("dev.clutcher.modulith:spring-modulith-module-archunit-starter:2.1.0")
}
Using Maven:
<dependencies>
<dependency>
<groupId>dev.clutcher.modulith</groupId>
<artifactId>spring-modulith-module-archunit</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>dev.clutcher.modulith</groupId>
<artifactId>spring-modulith-module-archunit-starter</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Basic Usage
Verifying Modules with Spring Boot Test
Set up a test class to verify module architecture using Spring Modulith’s module verification tools and Spring Modulith Module ArchUnit.
import dev.clutcher.modulith.archunit.verifier.app.api.ApiForModuleArchitectureVerification;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.modulith.core.ApplicationModules;
@SpringBootTest
class ApplicationModulesTests {
@Autowired
private ApiForModuleArchitectureVerification moduleArchitectureVerification;
@Test
void verifyModules() {
ApplicationModules applicationModules = ApplicationModules.of(Application.class);
applicationModules.forEach(System.out::println);
applicationModules.verify();
moduleArchitectureVerification.verifyAllModules(applicationModules);
}
}
Creating Custom Architecture Rules
An ApiForArchRuleCreation bean is an architecture profile: its isApplicable picks the modules it checks, and the verifier runs every profile bean next to the default hexagonal one. To check the modules of another architecture, declare a profile for them with ApiForCustomizingArchRuleCreation:
@Configuration
public class ModuleArchitectureRulesConfiguration {
@Bean
public ApiForArchRuleCreation layeredArchRuleCreation() {
return ApiForCustomizingArchRuleCreation
.forApplicabilityChecker((module, allClassesRelatedToModule) -> isLayeredModule(module))
.withLayerRule(module -> createLayeredArchitectureRule(module))
.create();
}
}
To replace the default hexagonal profile, switch it off with dev.clutcher.modulith.archunit.rules.hexagonal.enabled=false and declare your own, for example the default one with a replaced group:
@Bean
public ApiForArchRuleCreation customizedHexagonalArchRuleCreation(HexagonalArchitectureSettings settings,
ArchRuleRegistry registry) {
HexagonalArchRuleCreationService defaultHexagonalRuleCreationService =
new HexagonalArchRuleCreationService(settings, registry);
return ApiForCustomizingArchRuleCreation
.forExistingArchRuleCreation(defaultHexagonalRuleCreationService)
.withPackageStructureRule(module -> null)
.create();
}
To add a single rule to a group of the default rule set, declare it as a NamedArchRule bean. The starter registers it next to the default rules, and its ID can be toggled like theirs:
@Bean
public NamedArchRule noSchedulingInDomainRule() {
return new NamedArchRule("no-scheduling-in-domain", RuleGroup.DEV_STANDARDS,
(moduleBasePackage, settings) -> ArchRuleDefinition.noClasses()
.that().resideInAPackage(moduleBasePackage + settings.getDomainPackageMatcher())
.should().beAnnotatedWith("org.springframework.scheduling.annotation.Scheduled")
.allowEmptyShould(true));
}
Rule Groups
Rules are organized into four groups, each independently toggleable:
| Group |
Purpose |
Library |
LAYER |
Layer dependency enforcement (which layers may access which) |
HexagonalArchitectureRulesLibrary |
PACKAGE_STRUCTURE |
Valid package placement within modules |
HexagonalArchitectureRulesLibrary |
DEV_STANDARDS |
Contracts of the hexagonal building blocks: each rule is scoped to a package of the settings, such as the ports, the adapters, the services or the domain model |
HexagonalArchitectureRulesLibrary |
CODE_CONVENTIONS |
Conventions for every class of a module, whatever its package and architecture |
CodeConventionsRulesLibrary |
A rule belongs to DEV_STANDARDS when it needs a package of the hexagonal settings to say where it applies, and to CODE_CONVENTIONS when it applies to the whole module.
Default Rules for Hexagonal Architecture
This library enforces opinionated rules for hexagonal architecture, which can be either adopted as is or customized. Exact rules can be found in HexagonalArchitectureRulesLibrary and CodeConventionsRulesLibrary.
Package Structure
some-module/
├─ app/
│ ├─ api/ # Driving ports (primary ports)
│ │ └─ ApiForDoingSomething.java
│ ├─ domain/
│ │ ├─ services/ # Application services
│ │ │ └─ DoingSomethingService.java
│ │ └─ model/ # Domain model
│ │ └─ Object.java
│ └─ spi/ # Driven ports (secondary ports)
│ └─ SomeRepository.java
├─ in/ # Driving adapters (primary adapters)
│ └─ rest/
│ └─ SomeRestController.java
└─ out/ # Driven adapters (secondary adapters)
└─ db/
└─ SomeRepositoryUsingMysql.java
another-module/
├─ app/
│ ├─ api/
│ │ └─ ApiForDoingSomethingElse.java
To conform with hexagonal architecture package structure most ensure that Adapters are placed outside application root, while Ports are inside application root.
Layers Structure
- Driving Ports (
app.api)
Defines interfaces for application intent. Example: ApiForDoingSomething.
- Driven Ports (
app.spi)
Defines interfaces for external dependencies, such as repositories or external services.
- Driving Adapters (
in)
Entry points for the application, e.g., REST controllers or event listeners.
- Driven Adapters (
out)
Implementations that interact with external systems, such as databases or messaging services.
- Application Services (
app.domain.services)
Implements the business logic of the module and interacts with ports.
- Application Configuration (
config)
Spring beans and module configurations.
Layer Dependency Rules
The library enforces strict layer dependency rules to ensure clean separation of concerns and adherence to hexagonal architecture.
- Layer Rules:
- Driving Ports (
app.api) can be accessed only by:
- Driving Adapters (
in),
- Application Services (
app.domain.services),
- Application Configuration (
config).
- Driven Ports (
app.spi) can be accessed only by:
- Driven Adapters (
out),
- Application Services (
app.domain.services),
- Application Configuration (
config).
- Application Services (
app.domain.services) can be accessed only by:
- Driving Ports (
app.api),
- Driven Ports (
app.spi),
- Application Configuration (
config).
- Driving Adapters (
in) can be accessed only by:
- Application Configuration (
config).
- Driven Adapters (
out) can be accessed only by:
- Application Configuration (
config).
- Dependencies originating outside the module boundaries are ignored by default, ensuring only internal dependencies are considered during validation.
- Spring Modulith verify checks will ensure that module boundaries are not violated.
- To use Driving Ports in other submodules define it as Named Interface with
package-info.java
Layer and Package Structure
Rules of the LAYER and PACKAGE_STRUCTURE groups:
| Rule ID |
Group |
Description |
layer-definition |
LAYER |
Defines the six layers from the package settings, each optional, and enforces the access rules of Layer Dependency Rules; dependencies from classes outside the module are ignored |
domain-model-dependency-restriction |
LAYER |
Restricts the dependencies of the domain model, see below |
module-root-package-structure |
PACKAGE_STRUCTURE |
Every class of the module resides in the application root (app), the configuration (config), the driving adapters (in) or the driven adapters (out), so no class sits in the module base package itself or in another package |
application-ports-package-structure |
PACKAGE_STRUCTURE |
Every class in the application root (app) resides in the driving ports (app.api), the driven ports (app.spi), the application services (app.domain.services) or the domain model (app.domain.model) |
adapters-package-structure |
PACKAGE_STRUCTURE |
No class of the driving adapters (in) or the driven adapters (out) resides in the application root (app) |
Development Standards
Rules enforcing the contracts of the hexagonal building blocks:
| Rule ID |
Description |
driving-ports |
Driving ports (app.api) are interfaces whose names start with ApiFor; package-info is ignored |
driven-ports |
Driven ports (app.spi) are interfaces |
application-services |
Application services that implement a driving port are classes, not interfaces, whose names end with Service, ServiceBuilder or ServiceFactory |
driven-adapters |
Driven adapters that implement a driven port have Using in their names, such as RepositoryUsingJpa |
spring-adapter-naming |
Classes in the Spring driving adapters (in.spring) end with Adapter |
spring-adapter-public-parameter-types |
Parameter types of the public methods a Spring driving adapter declares start with Public; types from java.* packages are skipped |
api-method-parameter-type-naming |
Parameter types of the methods a driving port declares end with a suffix chosen by the method name, which is matched case-insensitively anywhere in the name and checked in this order: a name containing search or find → *Criteria, else create → *Attributes, else remove or delete → *Parameters; types from java.* packages are skipped |
domain-model-not-exposed-in-controllers |
Public methods of controllers do not return domain model types; the controller annotations are configurable and cover Spring MVC and Spring for GraphQL by default |
domain-model-only-records-or-pojos |
The domain model holds records, enums, subclasses of Exception or RuntimeException, sealed types, anonymous and synthetic classes, and POJOs; a POJO is a class that is not abstract, not an interface and not an annotation, with at least one instance field, every instance field private and each with a getX() or isX() getter without parameters |
no-data-postfix-in-domain-class-names |
Domain classes (app.domain) do not end with Data |
The domain-model-dependency-restriction rule of the LAYER group lets the domain model depend only on itself, java.*, lombok.*, slf4j and the packages of additional-domain-model-allowed-packages.
Code Conventions
Conventions for every class of a module:
| Rule ID |
Description |
no-dto-in-class-names |
Class names, also of nested request and response records, do not contain dto in any letter case |
no-impl-postfix |
Classes do not end with Impl; classes annotated with one of the generated-class-annotations are excluded, and that list is empty by default, so no class is excluded |
logger-field-naming |
SLF4J Logger fields are named LOGGER |
mapper-annotated-with-generated |
@Mapper classes have @AnnotateWith with an annotation named Generated, such as javax.annotation.processing.Generated or jakarta.annotation.Generated |
Configuring Default Rules
You can configure the architecture rules through Spring properties:
dev.clutcher.modulith.archunit.rules.hexagonal.package.port.driving = .api..
dev.clutcher.modulith.archunit.rules.hexagonal.package.port.driven = .spi..
dev.clutcher.modulith.archunit.rules.hexagonal.package.adapter.driving = .in..
dev.clutcher.modulith.archunit.rules.hexagonal.package.adapter.spring-driving = .in.spring..
dev.clutcher.modulith.archunit.rules.hexagonal.package.adapter.driven = .out..
dev.clutcher.modulith.archunit.rules.hexagonal.package.application.root = .app
dev.clutcher.modulith.archunit.rules.hexagonal.package.application.domain = .domain..
dev.clutcher.modulith.archunit.rules.hexagonal.package.application.domain-model = .domain.model..
dev.clutcher.modulith.archunit.rules.hexagonal.package.application.services = .domain.services..
dev.clutcher.modulith.archunit.rules.hexagonal.package.application.configuration = .config..
Value of application.root is automatically added to port.driving, port.driven, application.domain, application.domain-model and application.services to ensure that package structure after properties changes does not violate hexagonal architecture.
Generated Classes and Domain Model Dependencies
# Classes with these annotations are excluded from the no-impl-postfix rule; the default is empty, so no class is excluded
dev.clutcher.modulith.archunit.rules.hexagonal.package.generated-class-annotations=\
javax.annotation.processing.Generated,\
jakarta.annotation.Generated
# Extra packages the domain model may depend on, such as Spring Modulith for @NamedInterface
dev.clutcher.modulith.archunit.rules.hexagonal.package.additional-domain-model-allowed-packages=\
org.springframework.modulith..
Controller Annotations
By default, the library checks @RestController and @Controller for the domain-model-not-exposed rule. To add custom controller annotations (e.g., Netflix DGS):
dev.clutcher.modulith.archunit.rules.hexagonal.package.controller-annotations=\
org.springframework.web.bind.annotation.RestController,\
org.springframework.stereotype.Controller,\
com.netflix.graphql.dgs.DgsComponent
Toggling Individual Rules
Any rule can be disabled via Spring properties using the rule ID:
dev.clutcher.modulith.archunit.rules.toggle.no-dto-in-class-names=false
dev.clutcher.modulith.archunit.rules.toggle.domain-model-only-records-or-pojos=false
dev.clutcher.modulith.archunit.rules.toggle.logger-field-naming=false
Implementation Details
spring-modulith-module-archunit
- Architecture Rule Creation:
ApiForArchRuleCreation - Main entry point for creating ArchUnit rules
ApiForCustomizingArchRuleCreation - Main entry point for customizing existing instances of ApiForArchRuleCreation using DelegatingArchRuleCreationService
HexagonalArchRuleCreationService - Service for creating hexagonal architecture rule sets
DelegatingArchRuleCreationService - Service implementation to be used for custom rules creation
HexagonalArchitectureRulesLibrary - Library of predefined rules for hexagonal architecture (LAYER, PACKAGE_STRUCTURE, DEV_STANDARDS)
CodeConventionsRulesLibrary - Library of code convention rules for every class of a module (CODE_CONVENTIONS)
NamedArchRule - A rule with its ID and group, built per module from the module base package and the settings
ArchRuleRegistry - Holds the named rules and builds the rule of a group from the rules enabled by the toggle settings
- Architecture Rule Verification:
ApiForModuleArchitectureVerification - Main entry point to verify module architecture
ModuleArchitectureVerificationService - Service implementation for verifying module architecture
spring-modulith-module-archunit-starter
VerificationStrategyAutoconfiguration creates beans:
HexagonalArchitectureSettings
- Bean name:
hexagonalArchitectureVerificationProperties
- Implementation:
HexagonalPackageSettingsUsingSpringProperties, bound to the properties under dev.clutcher.modulith.archunit.rules.hexagonal.package
- Purpose: Holds hexagonal architecture configuration settings
- Dependencies: none
- It has no
@ConditionalOnMissingBean, so it is created even when the application declares its own HexagonalArchitectureSettings bean
ArchRuleToggleSettings
- Bean name:
archRuleToggleSettings
- Implementation:
ArchRuleToggleSettingsUsingSpringProperties
- Purpose: Reads which rule IDs are switched off under
dev.clutcher.modulith.archunit.rules.toggle
- Dependencies: none
ArchRuleRegistry
- Bean name:
archRuleRegistry
- Purpose: Registers the rules of both rule libraries and every
NamedArchRule bean of the application
- Dependencies:
ArchRuleToggleSettings, List<NamedArchRule>
ApiForArchRuleCreation
- Bean name:
hexagonalArchRuleCreationService
- Implementation:
HexagonalArchRuleCreationService
- Purpose: The default architecture profile, which checks the modules with hexagonal ports or adapters
- Dependencies:
HexagonalArchitectureSettings, ArchRuleRegistry
- Created unless
dev.clutcher.modulith.archunit.rules.hexagonal.enabled=false, also when the application declares profiles of its own
ApiForModuleArchitectureVerification
- Bean name:
applicationModulesArchitectureVerifier
- Implementation:
ModuleArchitectureVerificationService
- Purpose: Checks each module with every architecture profile that applies to it
- Dependencies:
List<ApiForArchRuleCreation>, so modules of different architectures are checked by their own profiles
Maintained by Igor Zarvanskyi, author of Laminar Software Design.
评论