What is Spring Modulith and how does it detect application modules?
Spring Modulith gives a modular monolith in Java two things. The first is an executable architecture check: a test that reads your package structure, derives a module model, and fails when code crosses a boundary it shouldn't. The second is a transactional event outbox: the event publication registry records domain events in the same transaction as the business change, so a listener in another module can't silently miss them.
The module model comes from package conventions. Spring Modulith takes the package of your main application class and treats each direct subpackage as an application module. Types in a module's top-level package are its public API. Anything in a nested subpackage is internal by default, and other modules may not reference it. You get encapsulation without splitting the build into separate artifacts.
That is why the layout matters. Suppose you organize by business capability, with com.acme.shop.order, com.acme.shop.inventory, and com.acme.shop.billing, each holding its own controllers, services, and persistence in nested packages. The detected modules then match how the team talks about the system, and a dependency from billing into order.internal is flagged as a real violation.
A layer-based layout works against this. With controller, service, and repository as top-level packages, you get three "modules" that restate your layering. They say nothing about which business capability owns which data, so the check enforces nothing useful.
The benefit is largest for a growing single codebase with several contributors, where boundaries erode through many small shortcuts. In a small codebase owned by one team, those boundaries are easier to keep in your head, and the payoff is weaker.
// Package layout organized by business capability:
//
// com.acme.shop
// ├── ShopApplication.java <- main class; its package is the root
// ├── order <- module "order"
// │ ├── OrderService.java <- public API (top-level package)
// │ └── internal <- internal by default
// ├── inventory <- module "inventory"
// └── billing <- module "billing"
//
// A layer-based root (controller/, service/, repository/) would yield three
// "modules" named after layers, which tells the check nothing about ownership.
package com.acme.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
class ModularityTests {
// Derive the module model from the package of the main application class.
ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
void printsDetectedModules() {
// Print the model to confirm it matches the intended design:
// expect order, inventory and billing, not controller/service/repository.
modules.forEach(System.out::println);
}
@Test
void verifiesModuleBoundaries() {
// Fails the build if, for example, billing references a type in
// com.acme.shop.order.internal, or if modules form a dependency cycle.
modules.verify();
}
}
A JUnit test that derives the module model from a capability-based package layout, prints the detected modules, and fails when one module reaches into another module's internal package.
How do you make module boundary violations fail the build?
The check itself is a plain unit test. Create a test class next to your @SpringBootApplication class and add one test method that calls ApplicationModules.of(Application.class).verify(). No Spring context starts. The call scans the classes under the application's base package, groups them into application modules by their direct sub-packages, and analyzes the type dependencies between those modules. If it finds a violation, verify() throws an exception that lists every offending dependency, and the test fails.
By default it rejects two kinds of problems:
- Cycles between modules. If
ordersdepends oninventoryandinventorydepends back onorders, directly or through other modules, the cycle is reported. Cycles mean neither module can be understood, tested or extracted on its own. - Access to another module's internal types. Only types in a module's base package make up its API. Types in nested packages are internal. If
ordersreferences a class ininventory.internal, that dependency is rejected, even if the class ispublicin Java terms.
Because this runs as an ordinary test, CI enforces it without any extra tooling. A pull request that adds a shortcut across a boundary fails during the test phase, alongside any broken unit test. The violation surfaces while the change is still small and the author still has the context to fix it.
Know the limit. verify() checks only static type dependencies in the analyzed bytecode. It cannot see coupling through a shared database schema, through two modules reading and writing the same tables, through reflection, or through string-based bean or class lookups. A passing test shows that the code respects the declared boundaries. It does not prove that the modules are independent.
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
// Plain JUnit test: no @SpringBootTest, so no application context starts.
class ModularityTests {
// Scans com.example.shop and treats each direct sub-package
// (orders, inventory, ...) as an application module.
private final ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
void verifiesModuleBoundaries() {
// Throws if modules form a dependency cycle, or if one module
// references types in another module's nested (internal) packages,
// e.g. orders -> inventory.internal.StockRepository.
// The exception lists every offending dependency, failing the build in CI.
modules.verify();
}
// Note: this only sees static type dependencies in bytecode.
// Shared tables, reflection and string-based lookups pass unnoticed.
}
A plain JUnit test that calls ApplicationModules.of(...).verify() so that module cycles and access to another module's internal types fail the test phase in CI.
How do you declare allowed dependencies and named interfaces?
By default, every module may use the public types in any other module's base package. Types in sub-packages are treated as internal. verify() enforces that, but it leaves two gaps. Any module can still depend on any other, and you sometimes need to expose something that does not belong in the root package.
Narrowing who a module may depend on
@ApplicationModule is placed on the module's package-info.java. Its allowedDependencies attribute lists the modules this module is permitted to use, for example "inventory" and "customer". Any other cross-module reference then fails verification. The point is to make each new dependency a visible, reviewed change to one annotation. Without that, an import slips in through autocomplete.
Exposing a deliberate API
To publish a sub-package such as order.spi without moving it to the root, annotate its package-info.java with @NamedInterface("spi"). Consumers can then reference it precisely in their own allowed dependencies with the "order :: spi" syntax.
Other modules then depend on a surface someone chose. They no longer depend on whatever a developer happened to mark public.
What this costs you
Declared boundaries add friction to refactoring. Moving a class between packages can break verification in modules you never touched. A cross-module change may also need annotation edits in several places. That friction is intentional, but expect pushback.
The bigger risk is the escape hatch: a shared or common module that every other module is allowed to use. It starts small and then collects DTOs, utilities and eventually business logic. Once that happens, your boundaries exist on paper while the coupling has moved into one module that everything depends on. Keep shared modules limited to stable, domain-free code, and question every addition.
// File: src/main/java/com/example/order/spi/package-info.java
// Publish this sub-package as the "spi" named interface of the order module.
// The rest of order's sub-packages remain internal.
@org.springframework.modulith.NamedInterface("spi")
package com.example.order.spi;
// File: src/main/java/com/example/shipping/package-info.java
// shipping may use only inventory's public API and order's "spi" interface.
// Any other cross-module reference, including order internals, fails verify().
// Adding a dependency is now a one-line change that shows up in review.
@org.springframework.modulith.ApplicationModule(
allowedDependencies = { "inventory", "order :: spi" }
)
package com.example.shipping;
// File: src/test/java/com/example/ModularityTests.java
package com.example;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
class ModularityTests {
@Test
void verifiesModuleBoundaries() {
// Fails the build if shipping imports anything outside its allowed list,
// for example com.example.order.internal or com.example.customer.
ApplicationModules.of(Application.class).verify();
}
}
The order module exposes its spi sub-package as a named interface. The shipping module restricts its dependencies to inventory and order :: spi, and a single verify() test fails the build when either rule is broken.
Bringing an existing codebase to a passing verify()
Start by adding a single test that builds the module model from your application class and calls verify(). Don't fix anything yet. The first run is an inventory: the failure message lists every cycle, every reference to a non-exposed type, and every dependency that isn't allowed. Save that list. It shows how far the code is from the structure you think it has.
Fix violations in a deliberate order
- Break cycles first. A cycle between two modules means neither can change independently, and it hides the real direction of dependency. Common fixes are replacing a direct call with a published event, or moving the shared concept into whichever module actually owns it.
- Move or expose internal types. For each reference into another module's internals, decide whether the type belongs in that module's API package, behind a named interface, or in the caller's own module. Exposing types just to get the test passing defeats the purpose.
- Tighten allowed dependencies last. Once the graph is acyclic and the APIs are honest, declare explicit
allowedDependenciesso new edges require a visible change.
The real cost
If the codebase is organized by layer, with packages such as controller, service, and repository, the verifier has nothing meaningful to check. You first have to regroup the code by business capability. That reorganization usually costs more than the tooling. Expect several rounds of arguing over which module owns customers, pricing, or notifications.
The payoff comes afterward. A boundary regression shows up as a failing build in a pull request, when it is cheap to fix. Without the check, you find it months later while trying to extract or refactor a module.
// src/test/java/com/example/shop/ModularityTests.java
// Step 1: inventory. Run this before fixing anything; the failure lists every violation.
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
class ModularityTests {
// Modules are derived from the direct sub-packages of ShopApplication's package.
ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
void verifiesModuleStructure() {
// Fails on cycles, references to non-exposed types, and disallowed dependencies.
modules.verify();
}
}
// src/main/java/com/example/shop/inventory/api/package-info.java
// Step 2: expose a deliberate API instead of letting callers reach into internals.
@org.springframework.modulith.NamedInterface("api")
package com.example.shop.inventory.api;
// src/main/java/com/example/shop/orders/package-info.java
// Step 3: tighten last. Adding a new dependency now requires editing this file,
// which makes the change visible in review.
@org.springframework.modulith.ApplicationModule(
allowedDependencies = { "inventory::api", "customers" }
)
package com.example.shop.orders;
A verify() test that inventories violations, plus a named interface and an explicit allowedDependencies declaration, matching the expose-then-tighten steps of the migration.
How does the event publication registry deliver domain events?
Start with the most common coupling: an order service that calls the inventory service directly once an order completes. The order module now depends on inventory, and adding a third consumer means editing order code. Instead, have the order module publish an OrderCompleted event through Spring's ApplicationEventPublisher inside its @Transactional method. The order module states that something happened and does not know who reacts to it.
On the consuming side, annotate the handler with @ApplicationModuleListener. This annotation combines three behaviors. The listener is a transactional event listener that fires only after the publishing transaction commits. It runs asynchronously. It runs in a new transaction of its own. As a result, a failure in inventory cannot roll back the order, and a rolled-back order never triggers inventory work.
The event publication registry makes this reliable. When the event is published, the registry writes one publication record for each transactional listener, in the same transaction as the business change. When a listener completes successfully, its record is marked complete. If the process crashes before that, the record stays incomplete and can be resubmitted. You get at-least-once delivery, the same guarantee as an outbox, without writing outbox tables yourself. Choose the persistence starter that matches your existing store, such as JPA, JDBC or MongoDB, so the records share the transaction with your data.
Trade-offs
- Eventual consistency. A user may see a completed order before inventory reflects it.
- Idempotent listeners. Redelivery means a listener can process the same event more than once, so it must tolerate duplicates.
- No ordering. Do not depend on ordering across listeners or across events.
- In-process only. Delivery stays inside the application unless you configure event externalization separately.
How do you operate the event publication registry in production?
Each publication row records the event, the target listener and a completion timestamp. Rows without a completion date are incomplete: either the listener threw an exception, or the application stopped before the listener finished. The IncompleteEventPublications API lets you look these up and resubmit them, either all at once, by a predicate, or only those older than a given duration. The age filter matters because a recent incomplete entry may still be in flight.
Restart resubmission versus an explicit job
Spring Modulith can republish outstanding events at startup. This setting is off by default. Turning it on is convenient, but it has a known failure mode. Suppose an event fails because of bad data or a bug. That poison event is replayed on every restart. During a crash loop or a rolling deploy, the same failure repeats on every instance.
For most production systems, a scheduled job is the safer choice. The job calls the age-filtered resubmission method, which keeps retries bounded and observable. It also lets you exclude events that are known to be bad.
Housekeeping
Completed entries remain in the table by default. The CompletedEventPublications API can delete them, either all of them or those older than a cutoff. Run that deletion on a schedule. Depending on your version, the completion mode may also be configurable, so entries can be deleted or moved to an archive table when they complete.
Monitoring
A failed listener does not roll back the publisher, so failures are easy to miss. Alert on two signals:
- The count of incomplete publications older than your retry window.
- Listener exceptions in your logs.
Cost
Every publication adds writes inside the business transaction. Completion and cleanup add more. Measure the throughput impact on your own workload rather than assuming it is negligible.
How do you test a single module and generate its documentation?
Bootstrapping one module
Annotating a test class with @ApplicationModuleTest starts a Spring context that contains only the module the test class's package belongs to. This keeps tests fast. It also exposes hidden coupling: if the module needs a bean from another module, the context fails to start. You then either provide a mock for that bean or widen the bootstrap mode deliberately:
STANDALONE(the default) loads only the module under test.DIRECT_DEPENDENCIESalso loads the modules it depends on directly.ALL_DEPENDENCIESloads the full transitive dependency graph.
If a test only passes under ALL_DEPENDENCIES, the module is probably more entangled than its declared dependencies suggest.
Asserting on events
Add a PublishedEvents or AssertablePublishedEvents parameter to a test method. Spring Modulith captures every event published during that test, so you can filter by type and check payload fields. This avoids registering throwaway listeners.
A Scenario parameter handles asynchronous flows. You start a stimulus, either by publishing an event or by calling a service. You then wait for a resulting event of a given type, or for a state change you poll for. The scenario waits with a timeout instead of Thread.sleep, which keeps @ApplicationModuleListener handlers deterministic in tests.
Documentation from the same model
Documenter takes the same ApplicationModules instance that verify() uses. It writes these into the build output:
- C4 or UML component diagrams for the whole application and for each module.
- Module canvases listing each module's Spring beans, aggregates, published and consumed events, and configuration properties.
Generate these documents in a test so they are rebuilt on every build. Diagrams produced that way cannot drift from the code they describe.
When should you avoid Spring Modulith, and what are the alternatives?
Spring Modulith pays off when several people or teams share one deployable and the domain splits into a handful of business capabilities. Skip it for a small single-team codebase, where code review already catches boundary drift and the extra annotations and test add little. Also skip it for code organized by technical layer (controller, service, repository) that the team cannot restructure. Module detection assumes top-level packages represent business capabilities, so layer packages produce modules that depend on one another in a chain. The resulting violations describe nothing useful.
| Approach | Enforcement strength | Event delivery guarantee | Development cost | Operational overhead |
|---|---|---|---|---|
| Package conventions + code review | None beyond reviewer attention | None built in | Very low | None |
| Spring Modulith | Test-time, fails the build if verification runs | At-least-once via the registry, persisted in the business transaction | Low to moderate | Registry table and incomplete-publication handling |
| Maven/Gradle subprojects | Compile-time, via declared dependencies | None built in | Moderate, more build configuration | Low |
| JPMS modules | Compile-time and runtime encapsulation | None built in | High, friction with reflection-heavy frameworks | Low |
| Architecture rule tests | Test-time, rules you write yourself | None built in | Moderate, you maintain the rules | None |
| Hand-written transactional outbox | None | At-least-once, if implemented correctly | High | Outbox table, relay process, cleanup |
| Separate services + message broker | Physical, enforced by network boundaries | Depends on broker and producer configuration | High | Highest: deployments, broker, distributed failure modes |
These approaches combine. Build-level subprojects give compile-time checks for the few boundaries that must never break. Spring Modulith then covers finer-grained modules and event delivery inside each subproject. Move to separate services only when you need independent deployment or scaling, not to enforce boundaries.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring modulith, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.