Enforce Module Boundaries Java Rules With ArchUnit
Enforce package and module boundaries in Java with ArchUnit rules and Spring Modulith's verify, so architecture decisions fail the build instead of drifting.

Every project begins with an intended structure: features independent, controllers not touching repositories, the domain free of framework imports. Six months later, it is whatever the shortest path produced. A test can hold the line.
ArchUnit
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<version>1.4.1</version>
<scope>test</scope>
</dependency>@AnalyzeClasses(packages = "com.example.shop", importOptions = ImportOption.DoNotIncludeTests.class)
class ArchitectureTest {
@ArchTest
static final ArchRule domainDoesNotDependOnSpring =
noClasses().that().resideInAPackage("..domain..")
.should().dependOnClassesThat().resideInAnyPackage("org.springframework..", "jakarta.persistence..");
@ArchTest
static final ArchRule controllersDoNotTouchRepositories =
noClasses().that().resideInAPackage("..web..")
.should().dependOnClassesThat().resideInAPackage("..persistence..");
@ArchTest
static final ArchRule noCycles =
slices().matching("com.example.shop.(*)..").should().beFreeOfCycles();
@ArchTest
static final ArchRule servicesAreNotFieldInjected =
noFields().should().beAnnotatedWith(Autowired.class);
}Each rule reads in English and fails with the offending class and line:
Architecture Violation: Rule 'no classes that reside in a package '..domain..' should depend on classes that reside in any package ['org.springframework..']' was violated (1 times):
Field <com.example.shop.orders.domain.Order.clock> has type <org.springframework.stereotype.Component> in (Order.java:12)Layered rules use layeredArchitecture():
layeredArchitecture().consideringOnlyDependenciesInLayers()
.layer("Web").definedBy("..web..")
.layer("Application").definedBy("..application..")
.layer("Domain").definedBy("..domain..")
.whereLayer("Web").mayNotBeAccessedByAnyLayer()
.whereLayer("Domain").mayOnlyBeAccessedByLayers("Application", "Web");This is the executable form of the structure discussed in layered architecture and hexagonal architecture.
Spring Modulith
Spring Modulith treats each direct sub-package of the main package as an application module, and can check the module structure:
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-starter-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.modulith</groupId>
<artifactId>spring-modulith-starter-test</artifactId>
<scope>test</scope>
</dependency>class ModularityTests {
ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
void verifiesModuleStructure() {
modules.verify();
}
@Test
void writesDocumentation() {
new Documenter(modules).writeModulesAsPlantUml().writeIndividualModulesAsPlantUml();
}
}verify() fails if a module reaches into another's internal package, if there are cycles, or if a module uses a type it has not declared as an allowed dependency. Types in a module's base package are its public API, and sub-packages are internal by default. The Documenter produces diagrams that cannot lie, because they come from the code. The idea in practice is in Spring Modulith and the layout in package by feature.
Adopting rules in an old codebase
A project with hundreds of violations cannot turn on a rule that fails the build. Use freezing:
@ArchTest
static final ArchRule rule = FreezingArchRule.freeze(
noClasses().that().resideInAPackage("..web..").should().dependOnClassesThat().resideInAPackage("..persistence.."));ArchUnit stores the current violations in a file, and fails only on new ones. As you fix old ones the stored set shrinks. That turns a rule from a wish into a ratchet.
Choosing rules
- Rules that protect a decision you have made and would argue for in review.
- Rules about dependencies and annotations, which are objective. Skip style preferences that a formatter covers.
- Few rules with clear messages. Add a
.because("...")to explain the reason:
.should().notBe(...).because("the domain must be testable without Spring")A failing rule that nobody understands gets deleted or suppressed.
Speed
ArchUnit imports the class files once per test class and caches it. The suite runs in seconds. Keep it in the regular test phase, so it runs locally as well as in CI. Where the unit test layer sits in the overall approach is in the testing strategy.
What a useful rule looks like
The rules that survive are the ones that name a real incident. "Controllers must not use repositories" exists because somebody once queried the database from a controller and skipped the transaction. "Feature packages may only call each other through their public package" exists because a change in billing once broke orders in a way nobody saw in review. When you write a rule, put the story in the because(...) message, so a failing build explains itself to a developer who was not there:
noClasses().that().resideInAPackage("..web..")
.should().dependOnClassesThat().resideInAPackage("..persistence..")
.because("web code goes through a service so the transaction boundary stays in one place")
.check(classes);A rule without a reason gets deleted the first time it blocks someone in a hurry, and with a reason it gets argued with, which is better.
Cycles are the first rule to add
Before layers and slices, add the one rule that costs nothing to explain: no cyclic dependencies between top-level packages. ArchUnit's slices().matching("dev.javahacks.shop.(*)..").should().beFreeOfCycles() finds them in a few lines. A cycle between orders and billing means neither can be understood, tested or extracted without the other, and it is almost always created by one convenient import. Fixing the first few cycles in an old codebase is real work, so freeze the existing violations with ArchUnit's FreezingArchRule, which records them in a file and fails only on new ones. The count then goes down over months instead of blocking every build on day one.
Keeping the test fast and trustworthy
Import the classes once per test class, not once per rule, by caching the JavaClasses in a static field or using the @AnalyzeClasses annotation, because scanning a large classpath takes seconds. Exclude test classes and generated code from the import with ImportOption.DoNotIncludeTests, or the rules fail on things nobody wrote. Make sure the rule can fail: when you write a new one, break it deliberately in a scratch change and watch the build go red. A rule whose package pattern has a typo matches zero classes, passes, and protects nothing. Recent ArchUnit versions fail on an empty rule set by default, and if yours does not, add .allowEmptyShould(false) through the configuration property so the typo is loud.
Documenting the structure with Modulith
Spring Modulith can generate documentation from the same model it verifies. new Documenter(modules).writeModulesAsPlantUml() writes a diagram of modules and their dependencies, and writeModuleCanvases() writes a short description of each module: its public types, the events it publishes and the ones it listens to. Because the output is generated from the code and the verification runs in the build, the diagram cannot go stale the way a hand-drawn one does. Commit the generated files or publish them from CI, and a new developer gets an accurate map on the first day.
Events are the mechanism that keeps modules decoupled in a Modulith. A module publishes an OrderPlaced event and others react, without the publisher importing them. The compiler no longer enforces that dependency, so the event types become the real contract, and they deserve the same care as a public API: stable names, immutable records, and no leaking of internal entities.
What to do when a rule fails in CI
A failing boundary test is a design conversation, not an obstacle. Read the message, which lists the exact class and the exact dependency. There are three honest responses. Move the code to where it belongs, if it was misplaced. Introduce a public interface or an event, if the dependency is legitimate and needs a doorway. Or change the rule, if the rule was wrong, and say why in the commit. The dishonest response, adding an exclusion to make the build pass, should be rare and reviewed, and every exclusion gets a ticket number in a comment.
Where these checks run
Run the architecture tests with the normal unit test task, so they execute in every build and on every pull request. A separate slow job gets skipped and ignored. If the test class takes more than a few seconds, cache the imported classes, as above, instead of moving the tests out of the default run.
Where this does not apply
Rules do not fix a design, they stop it from getting worse. For runtime boundaries between services, contract tests are the equivalent. The reference is the ArchUnit user guide, and the Spring Modulith reference describes verification.


