Pre-built ArchUnit rules for enforcing module boundaries in modular monolith architectures.
Modulith Rules runs entirely at test time. It has no runtime footprint, no framework coupling, and no impact on your production classpath.
Modulith Rules is published to Maven Central under the io.modularmonolith group id;
the current release is v0.3.0. The sources on main carry the next development
version (0.4.0-SNAPSHOT); to work against unreleased changes, build from source
(see Installing).
| Version | |
|---|---|
| Java | 17 or newer (CI builds on 17 and 21) |
| ArchUnit | 1.5.0 |
| JUnit | 6.1.3 (JUnit Platform) |
| Spring Boot | 4.1.1 (optional, only for modulith-rules-spring) |
These are the versions the library is built and tested against. The core module uses only long-stable ArchUnit APIs, so older ArchUnit and JUnit 5 lines are likely to work, but they are not covered by CI, so verify before relying on them.
Spring dependencies in modulith-rules-spring are provided scope: you bring your own
Spring version, and nothing Spring-related is added to your runtime classpath.
Add the core module in test scope:
<dependency>
<groupId>io.modularmonolith</groupId>
<artifactId>modulith-rules-core</artifactId>
<version>0.3.0</version>
<scope>test</scope>
</dependency>Add modulith-rules-spring as well if you want the Spring-specific rules:
<dependency>
<groupId>io.modularmonolith</groupId>
<artifactId>modulith-rules-spring</artifactId>
<version>0.3.0</version>
<scope>test</scope>
</dependency>If you use both modules, import the BOM once and drop the versions from the individual dependencies:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.modularmonolith</groupId>
<artifactId>modulith-rules-bom</artifactId>
<version>0.3.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>To work against unreleased changes instead, build from source and depend on the
0.4.0-SNAPSHOT version:
git clone https://github.com/modular-monolith/modular-monolith-rules.git
cd modular-monolith-rules
mvn clean installIf you want the shortest possible route, the quickstart folder holds a
drop-in ArchitectureTest.java, the Maven and Gradle snippets, and an archetype that
generates a two-module project with the test already in place.
The fastest path is convention-based: each module's base package is derived as
<rootPackage>.<moduleName>.
@AnalyzeClasses(packages = "com.example")
class ArchitectureTest {
@ArchTest
static final List<ArchRule> rules =
ModulithRules.forPackage("com.example", "ordering", "payments", "inventory")
.allRules();
}Note that allRules() is deliberately narrow. It returns exactly three rules:
allowed-dependency enforcement, internal-package protection, and cycle detection.
Use allCoreRules() for the full core set, which adds API-only cross-module access
and communication contract enforcement; both added rules skip anything you have not
declared, so the list is safe on any configuration. Spring rules are separate either
way (see Applying rules).
ModuleDefinition.builder(name) requires a basePackage. Omitting it throws
IllegalStateException: basePackage must be set for module '<name>', so set it on every
module you build by hand:
private static final ModulithRuleSet RULE_SET = ModulithRuleSet
.forRootPackage("com.example")
.module(ModuleDefinition.builder("ordering")
.basePackage("com.example.ordering") // required
.apiPackages(".api.")
.internalPackages(".internal.", ".infrastructure.")
.allowedDependencies("inventory", "payments")
.communicatesWith("notifications", CommunicationType.ASYNCHRONOUS)
.build())
.module(ModuleDefinition.builder("payments")
.basePackage("com.example.payments")
.apiPackages(".api.")
.internalPackages(".internal.")
.build())
.build();The ModulithRuleSet.Builder also offers shorthands that fill in the base package for
you, which is why the quick-start example above needs no basePackage:
ModulithRuleSet.forRootPackage("com.example")
.modules("ordering", "payments") // com.example.ordering, ...
.module("billing") // com.example.billing
.module("legacy", "com.acme.legacy") // explicit base package
.build();Most teams arrive here already using ArchUnit, or already looking at Spring Modulith, so it helps to say plainly where this library sits between them.
Plain ArchUnit gives you the assertion language and leaves the module model to you. That is fine for one or two rules, and it starts to hurt when a dozen modules each need their internal packages protected, their allowed dependencies declared and their cycles caught, because every team ends up writing the same fifteen rules with slightly different bugs. Modulith Rules is those rules, written once, with a module definition the rules share and failure messages that say what to change.
Spring Modulith models modules from the Spring application structure and brings
runtime features with it: event publication registries, observability, documentation
from the application context. If you are all-in on Spring and want that runtime story,
it is the more complete choice. Modulith Rules stays at test time, knows nothing about
your runtime, and does not need Spring at all. The modulith-rules-spring module adds
rules that understand @Repository, @Transactional and the rest, but the core works
on any codebase that uses packages. Teams running both are not unusual: Spring Modulith
for the runtime model, Modulith Rules for the stricter boundary and communication
contracts.
| Plain ArchUnit | Spring Modulith | Modulith Rules | |
|---|---|---|---|
| Module model | You define it per rule | Derived from Spring application packages | Declared once, fluent API or YAML |
| Runs | Test time | Test time and runtime | Test time only |
| Framework coupling | None | Spring | None in core; optional Spring module |
| Communication contracts (sync, async, none) | Write your own | Event-centric | Declared per module pair and enforced |
| Cycle detection | Slices API, manual setup | Yes | Yes, with the cycle named in the failure |
| Fix suggestion in the failure message | No | No | Yes |
Nothing special is needed because the rules are ordinary tests. A minimal GitHub Actions job that runs them on every pull request:
name: Architecture
on: [pull_request]
jobs:
architecture:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: 21
distribution: temurin
cache: maven
- run: mvn --batch-mode test -Dtest=ArchitectureTest -Dsurefire.failIfNoSpecifiedTests=falseRunning the architecture test on its own keeps the signal clear in the pull request checks, and it is usually fast enough to sit before the full suite.
Teams running Modulith Rules in their builds are listed in ADOPTERS.md. If that is you, add your team through the adopter issue template; a name and one sentence is plenty.
ModulithRules rules = ModulithRules.of(RULE_SET);
rules.boundaryRules().internalsShouldNotBeAccessedFromOutside().check(classes);
rules.cycleRules().noModuleCycles().check(classes);
rules.communicationRules().allCommunicationContractsRespected().check(classes);Spring rules live in their own factory, built from the same rule set with the same
of(...) style:
SpringModulithRules springRules = SpringModulithRules.of(RULE_SET);
springRules.repositoriesShouldBeModuleInternal().check(classes);
springRules.allRules().forEach(rule -> rule.check(classes));| Rule | What it checks |
|---|---|
modulesOnlyDependOnAllowedModules() |
Each module only depends on modules declared in allowedDependencies |
internalsShouldNotBeAccessedFromOutside() |
Internal packages are not accessed from other modules |
crossModuleAccessOnlyThroughApi() |
Cross-module access goes through declared API packages only |
moduleShouldHaveNoDependencies(name) |
A specific module has zero outgoing dependencies |
moduleShouldOnlyBeAccessedBy(name, ...) |
Only the listed modules may access the named module |
noModuleAccessesInternalsOfOthers() |
Alias for internalsShouldNotBeAccessedFromOutside() |
onlyAllowedDependenciesAreUsed() |
Alias for modulesOnlyDependOnAllowedModules() |
| Rule | What it checks |
|---|---|
noModuleCycles() |
No circular dependencies exist between any modules |
moduleHasNoCycles(name) |
A specific module does not participate in any cycle |
noCircularDependenciesBetweenModules() |
Alias for noModuleCycles() |
CycleRules.detectCycles(Map<String, Set<String>>) is public and static, so you can run
the DFS cycle detection against a hand-built graph without importing any classes.
Declare a contract with .communicatesWith(targetModule, CommunicationType). Contracts
are directional. They are declared on the calling module and describe how it may
reach the target.
| Rule | What it checks |
|---|---|
asyncModulesShouldNotCallDirectly() |
Modules with an ASYNCHRONOUS contract make no direct synchronous calls |
noCommModulesShouldNotInteract() |
Modules with a NONE contract have no dependency at all |
allCommunicationContractsRespected() |
Both of the above in a single rule |
CommunicationType.SYNCHRONOUS is a documentation-only declaration; no rule enforces it,
because direct calls are exactly what it permits.
Requires the
modulith-rules-springartifact.
| Rule | What it checks |
|---|---|
controllersShouldNotCrossModuleBoundaries() |
@Controller / @RestController beans do not depend on controllers in other modules |
repositoriesShouldBeModuleInternal() |
@Repository beans are only accessed from within their own module |
transactionalMethodsShouldNotSpanModules() |
@Transactional methods do not call across module boundaries |
eventClassesShouldBeInApiPackages() |
Event classes used by other modules live in API packages |
noDirectInjectionOfInternalBeans() |
No cross-module injection of beans outside the target's public API |
These rules inspect @Controller, @RestController, @Repository, @Transactional and
@Autowired, plus constructor parameters. @Service, @Component, @Configuration,
@Async and @Scheduled are not currently keyed off by any rule.
These defaults are deliberate, but they surprise people who expect every rule to fail closed. Each one causes a rule to skip rather than fail:
- Empty
allowedDependenciesmeans unrestricted. A module that declares no allowed dependencies is not checked bymodulesOnlyDependOnAllowedModules(). Declaring dependencies is what opts a module in. crossModuleAccessOnlyThroughApi()skips modules with noapiPackages. If the target module never declared an API package, there is nothing to enforce against.noDirectInjectionOfInternalBeans()behaves the same way.- Classes outside every declared module are ignored. Rules only reason about classes that fall inside a registered module's base package, so a dependency on an unregistered package is never a violation.
- Internal packages fall back to convention. With no
internalPackagesconfigured,.internal.and.infrastructure.are treated as internal. - Event accessors are exempt from async contracts. Under an
ASYNCHRONOUScontract, calls to a class whose simple name ends inEventare allowed, so readingevent.orderId()inside a listener is not reported as a synchronous call. ANONEcontract still forbids the dependency outright. - Module names must be unique. Registering the same name twice replaces the earlier definition, since modules are keyed by name.
See Declaring modules explicitly above.
Create src/test/resources/modulith-rules.yml:
root-package: com.example
modules:
ordering:
api-packages:
- .api.
internal-packages:
- .internal.
- .infrastructure.
allowed-dependencies:
- inventory
- payments
communication:
notifications: ASYNCHRONOUS
payments:
api-packages:
- .api.
internal-packages:
- .internal.Load it in your test:
@ArchTest
static final List<ArchRule> rules =
ModulithRules.of(ModulithConfigLoader.loadFromClasspath()).allRules();Other entry points: loadFromClasspath(fileName), loadFromFile(path), and
loadFromString(yaml).
The YAML parser is hand-written and covers only the subset shown above: no anchors,
flow style ([a, b]), multi-line scalars, or multi-document files. Indentation is
significant and must be exactly 2 spaces per level: module names at 2, properties at 4,
list items and communication entries at 6. Recognised keys are root-package, modules,
and per module base-package, api-packages, internal-packages,
allowed-dependencies, and communication. Unknown keys are silently ignored, so check
spelling if a setting seems to have no effect. base-package defaults to
<root-package>.<moduleName>, and a missing root-package throws IllegalStateException.
ModulithRules.forPackage("com.example", "ordering", "payments", "inventory").allRules();Derives each base package as com.example.<moduleName>, with no API or internal
declarations, which, per the notes above, means the API rule has nothing to enforce and
internal detection falls back to convention.
Every message names the offending element and the target package, then suggests a concrete fix. These are real messages produced by the test suite:
Module 'ordering': class com.example.ordering.internal.OrderServiceImpl depends on
com.example.inventory.api.InventoryService in module 'inventory', but 'inventory' is not
in the allowed dependencies [payments]. Fix: add 'inventory' to the allowedDependencies
of module 'ordering', or remove the dependency from
com.example.ordering.internal.OrderServiceImpl
Class com.example.ordering.internal.OrderServiceImpl in module 'ordering' accesses
com.example.payments.internal.PaymentServiceImpl which is in the internal package of
module 'payments'. Fix: expose a service interface in the module's api package, for
example com.example.payments.api, or move com.example.ordering.internal.OrderServiceImpl
into module 'payments' if it belongs there
Circular module dependency detected: cycleB -> cycleA -> cycleB. Fix: break the cycle by
moving the shared types into the api package of one of these modules, or extract them
into a separate module that both can depend on
OrderServiceImpl.placeOrder is @Transactional and calls
...payments.api.PaymentService in module 'payments', so the transaction spans both
modules. Fix: move the call out of the transactional method, or publish an event that
module 'payments' handles after the transaction commits
dependencyGraph().toMermaid(classes) renders the module graph as a Mermaid
flowchart string, ready to paste into any Markdown file:
String mermaid = ModulithRules.of(RULE_SET).dependencyGraph().toMermaid(classes);
System.out.println(mermaid);flowchart LR
inventory
notifications
ordering
payments
notifications -.-> ordering
ordering --> inventory
Every registered module appears as a node, including isolated ones. Solid
arrows are observed dependencies; an arrow renders dashed when the source
module declares communicatesWith(target, CommunicationType.ASYNCHRONOUS),
so the convention-based setup (which declares no contracts) renders all edges
solid. Output is deterministic: nodes sort by name and edges by source then
target, which keeps diffs clean when the diagram is committed. The method
never writes files; pipe the string wherever you want it.
mvn clean verify # full build: 53 tests across all three modules
mvn test # tests onlyRunning a single test class needs two flags that are easy to miss:
mvn -pl modulith-rules-spring -am test \
-Dtest=SpringModulithRulesTest \
-Dsurefire.failIfNoSpecifiedTests=false-am is required because modulith-rules-spring depends on modulith-rules-core, which
is not installed in your local repository during a partial build. And because -am also
builds core, where that test class does not exist, surefire needs
-Dsurefire.failIfNoSpecifiedTests=false to tolerate the empty match.
To inspect a violation message yourself, write a throwaway test that catches the error
instead of asserting on it, and check
modulith-rules-<module>/target/surefire-reports/<class>.txt, because surefire buffers
stdout rather than printing it to the console:
try {
rule.check(classes);
} catch (AssertionError e) {
System.out.println(e.getMessage());
}See RELEASING.md for the workflow, the secrets it needs, and the things that have gone wrong before.
| Artifact | Purpose |
|---|---|
modulith-rules-bom |
Bill of materials: import once to align the versions of all modulith-rules artifacts. |
modulith-rules-core |
Boundary, cycle, and communication rules. Fluent API and YAML loader. No Spring dependency. |
modulith-rules-spring |
Spring Boot rules for controllers, repositories, transactions, events, and injection. |
modulith-rules-example |
Working example project. Doubles as an end-to-end test of the published rules. |
Test fixtures live under io.modulith.rules.testfixtures (core) and
io.modulith.rules.testfixtures.spring (Spring). Each fixture module mirrors the
api / internal split that the rules expect, with deliberately violating and
deliberately clean arrangements so both branches of every rule are exercised.
Modulith Rules is a focused architecture-testing library built on ArchUnit. Spring Modulith is a broader toolkit for building modular Spring Boot applications. Both support architecture verification during tests.
Spring Modulith already provides built-in checks for module cycles, access
to internal packages, and explicitly allowed dependencies through
ApplicationModules.verify(). It also provides module integration testing,
generated documentation, and optional runtime features such as event
publication infrastructure and observability.
Modulith Rules focuses on configurable architecture policies: module boundaries, dependency cycles, directional communication contracts, and opinionated Spring-specific checks. Its core module has no Spring dependency.
| Concern | Modulith Rules | Spring Modulith |
|---|---|---|
| Primary focus | Configurable ArchUnit rules for modular monoliths | Modularity toolkit for Spring Boot applications |
| Architecture verification | Runs during tests | Runs during tests; optional startup verification is also available |
| Production classpath | Nothing added when used in test scope | Verification can be used in test scope; runtime features require corresponding production dependencies |
| Framework dependency | Framework-independent core; optional Spring rules | Designed for Spring Boot applications |
| Module configuration | Fluent Java API, YAML, or package conventions | Package conventions, annotations, and customization APIs |
| Built-in structural checks | Allowed dependencies, internal-package protection, API-only access, and cycles | Module cycles, internal access, and explicitly allowed dependencies |
| Additional architecture policies | Directional communication contracts and Spring-specific rules for controllers, repositories, transactions, events, and injection | Extensible verification with support for additional checks |
| Module integration testing | Not provided | Supported |
| Runtime event publication and observability | Not provided | Available through optional modules |
Choose Modulith Rules when you want a framework-independent architecture rule library, external module configuration, or its specific communication and Spring architecture policies.
Choose Spring Modulith when you want an integrated Spring Boot modularity toolkit covering structural verification, module integration testing, documentation, and optional runtime capabilities.
The two can be used together when Modulith Rules provides additional policies you need. If Spring Modulith already covers your requirements, adding another library may be unnecessary.
See the Spring Modulith documentation for its verification model and available features.
See CONTRIBUTING.md.
Apache License 2.0. See LICENSE.