What is Spring Modulith and how does it decide what an application module is?
Spring Modulith is a Spring project that treats your package structure as an architecture you can test. In a modular monolith you have no network boundary to stop one feature from reaching into another's internals. Spring Modulith adds that check: it analyzes your code and fails a test when a module depends on something it shouldn't.
The rule for finding application modules is simple. Every direct sub-package of the package containing your @SpringBootApplication class is a module. Each module's top-level package is its public API. Anything in a nested sub-package is internal to that module, even if the Java type is declared public. This matters because Java's public modifier alone can't say "public to my module only." The package convention fills that gap without extra build modules.
com.example.shop (@SpringBootApplication)
├── orders module
│ └── internal
├── inventory module
│ ├── InventoryService API
│ └── internal
│ └── StockRepository internal
└── shipping module
orders ──► inventory.InventoryService allowed
orders ──► inventory.internal.StockRepository forbidden
shipping ──► orders ──► shipping forbidden (cycle)
Legal reference from orders |
Illegal reference from orders |
|---|---|
com.example.shop.inventory.InventoryService |
com.example.shop.inventory.internal.StockRepository |
| Calls through the module's published API | Couples orders to how inventory stores stock |
Spring Modulith is released separately from Spring Boot and has its own release cadence. Before you add it, check the compatibility matrix in the official Spring Modulith documentation to find the version that matches your Spring Boot version.
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
// Lives in the same package as the @SpringBootApplication class,
// so orders, inventory and shipping are detected as modules.
class ModularityTests {
// Builds the module model from the package structure under
// com.example.shop. No Spring context is started.
ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
@Test
void verifiesModuleBoundaries() {
// Fails the test if any module references another module's
// internal types (for example orders -> inventory.internal.StockRepository)
// or if modules form a dependency cycle (shipping -> orders -> shipping).
modules.verify();
}
@Test
void printsDetectedModules() {
// Prints each detected module with its base package and dependencies.
// Use this to confirm Spring Modulith sees the layout you intended.
modules.forEach(System.out::println);
}
}
A JUnit test that builds the application module model from the package under the @SpringBootApplication class and fails when a module uses another module's internal types or when modules form a dependency cycle.
Why use Spring Modulith, and who should adopt it?
Package conventions decay quietly. A developer under deadline imports a repository class from another domain, a reviewer misses it, and six months later the billing package can't change without breaking shipping. Spring Modulith turns those conventions into an executable check. You write one test that loads your application's module structure and verifies it. If someone introduces a dependency cycle between modules or reaches into another module's internal packages, the test fails and the build goes red. The rule lives next to the code and runs on every commit, so it never depends on someone remembering a wiki page.
Who benefits
- Teams on a single Spring Boot codebase with several domains. Orders, inventory, billing and notifications share one repository and one deployment, but each needs a clear owner and a stable surface. Verification keeps those surfaces stable as more people contribute.
- Teams that want to keep service extraction possible. A module that only talks to others through declared interfaces or events can later be moved into its own service with far less untangling. Without enforcement, that option quietly disappears.
- Platform engineers. Boundary verification is an ordinary test, so it slots into existing CI pipelines without extra tooling. Architecture rules get the same treatment as any other failing test.
What it does not give you
A modular monolith is still a monolith. It deploys as one artifact, scales as one process and fails as one unit. A memory leak in one module takes down all of them. You also can't release billing without releasing everything else. Spring Modulith enforces structure at build time. It provides no runtime isolation or independent deployment.
How do you inspect and verify module boundaries with ApplicationModules?
The first step is to see what Spring Modulith thinks your structure is. Call ApplicationModules.of(Application.class) in a test and print each module it returns. For every module, the output lists its base package, the Spring beans it contains, and the other modules it depends on. Read this before you write any assertions. If shared shows up as its own module when you meant it as a library package, or billing depends on orders when you didn't expect it to, you want to know before verification starts reporting failures.
Next, add a test that calls ApplicationModules.of(Application.class).verify(). It needs no Spring context, so it runs quickly. When it finds problems, it throws an exception that lists every violation it found.
Failing case 1: reaching into an internal package
Suppose orders imports inventory.internal.StockRepository. Subpackages of a module are internal by default, so verification reports that orders depends on a non-exposed type in inventory. The message names both the source type and the target type. The fix is to stop using the internal type directly. Either expose an API type in the inventory base package or move the logic behind an existing public service.
Failing case 2: a cycle
If orders calls billing and billing calls back into orders, verification reports a cycle and lists the path between the modules. To break it, keep the calls in one direction only. Then replace the reverse call with an application event, or extract the shared concept into a third module.
Because this is an ordinary JUnit test, CI runs it on every build without extra setup. A boundary violation fails the pipeline just like a broken assertion, so the module structure is checked automatically instead of relying on code review.
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
// Plain JUnit test: no Spring context is started, so it runs fast in CI.
class ModularityTests {
// Build the module model once from the @SpringBootApplication class.
// Each direct subpackage of com.example.shop (orders, inventory, billing, ...)
// is treated as an application module.
private final ApplicationModules modules = ApplicationModules.of(Application.class);
@Test
void printDetectedModules() {
// Print each module's base package, its Spring beans and the modules
// it depends on. Check this output before relying on verify().
modules.forEach(System.out::println);
}
@Test
void verifyModuleBoundaries() {
// Throws an exception listing every violation, for example:
// - orders using a type from inventory.internal (non-exposed type)
// - a cycle such as orders -> billing -> orders
// Any violation fails this test, and therefore the CI build.
modules.verify();
}
}
A JUnit test that prints the module model Spring Modulith detects and then calls verify(), which fails the build on internal-type access or dependency cycles.
How do @NamedInterface and allowedDependencies tighten the rules?
By default, only types in a module's base package count as its API, and everything in sub-packages is internal. That is often too coarse. A payment module might want to expose a set of SPI interfaces that live in payment.spi while keeping its persistence and mapping code hidden. Annotating that sub-package's package-info.java with @NamedInterface("spi") makes it a deliberate, named entry point. Other modules may reference it, and the rest of payment's internals stay off-limits.
allowedDependencies works from the other direction. Placed in @ApplicationModule on a module's base package-info.java, it lists the only modules this module may use, for example allowedDependencies = { "customer", "payment :: spi" }. The double-colon form narrows a dependency to one named interface instead of the whole module. Any other outgoing reference fails verification, even if it would otherwise be legal. The dependency graph becomes something you declare and review in a pull request, not something that emerges from whatever imports compiled.
Both tools can be undermined. If every sub-package gets a @NamedInterface so that violations stop appearing, the verification still passes, but it no longer distinguishes API from implementation. Treat each new named interface as a public contract you will have to maintain.
The second trap is a shared or common module that every other module is allowed to depend on. It starts with value types and slowly collects services, repositories and business rules. Once real logic lives there, modules are coupled through it, and the boundaries hold only on paper. Keep a shared kernel small and limited to stable, behaviour-light types.
// File: src/main/java/com/example/shop/payment/spi/package-info.java
// Expose only this sub-package of 'payment' as a named, deliberate API.
// payment.internal, payment.persistence etc. remain hidden from other modules.
@NamedInterface("spi")
package com.example.shop.payment.spi;
import org.springframework.modulith.NamedInterface;
// File: src/main/java/com/example/shop/order/package-info.java
// 'order' may depend on the whole 'customer' module, but only on the
// 'spi' named interface of 'payment'. Any other outgoing reference
// (e.g. to inventory, or to payment.internal) fails verification.
@ApplicationModule(
allowedDependencies = { "customer", "payment :: spi" }
)
package com.example.shop.order;
import org.springframework.modulith.ApplicationModule;
// File: src/test/java/com/example/shop/ModularityTests.java
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
class ModularityTests {
@Test
void verifiesModuleBoundaries() {
// Fails the build if any module reaches into another module's
// internals or uses a dependency not listed in allowedDependencies.
ApplicationModules.of(ShopApplication.class).verify();
}
}
Three files showing a @NamedInterface on payment.spi, an @ApplicationModule on order that restricts it to customer and payment's spi interface, and a test that runs ApplicationModules.verify() to enforce both rules.
How do application events and module-scoped tests help keep boundaries intact?
When the orders module calls an inventory service bean directly, the dependency is compile-time and synchronous. Publishing an OrderCompleted event and consuming it in inventory with @ApplicationModuleListener reverses that: orders no longer knows inventory exists. The annotation combines an asynchronous, after-commit transactional listener with a new transaction. As a result, the listener sees only committed data, runs off the caller's thread, and cannot roll back the publisher.
If an event must not be lost, enable the event publication registry. It records each publication in a database table before dispatch and marks it complete when the listener succeeds. This adds a table to migrate and monitor. Incomplete publications also need attention: someone must decide when to resubmit or purge them.
The trade-offs are real:
| Concern | Direct bean call | Application event |
|---|---|---|
| Control flow | Visible in the call stack | Spread across listeners |
| Consistency | Same transaction | Eventual |
| Failure | Rolls back the caller | Listener fails after commit |
@ApplicationModuleTest boots a single module in one of three modes:
- Standalone loads only that module.
- Direct dependencies also loads the modules it depends on directly.
- All dependencies loads the full dependency tree.
Mock the beans of neighbouring modules that you leave out. Assert outcomes with PublishedEvents, or use the Scenario API to stimulate the module and wait for the expected event or state change. Narrow modes can hide missing beans and miswired configuration, so keep at least one full-context test.
The same suite can run Documenter to write PlantUML or C4 diagrams and module canvases. Because the documentation is generated from the code on each build, it cannot drift from it.
// File: inventory/InventoryUpdater.java (inventory module)
import org.springframework.modulith.events.ApplicationModuleListener;
@Component
class InventoryUpdater {
// Runs asynchronously after the orders transaction commits, in its own new
// transaction. A failure here cannot roll back the completed order.
@ApplicationModuleListener
void on(OrderCompleted event) {
// reserve or decrement stock for event.orderId()
}
}
// File: order/OrderModuleTests.java (orders module test)
import org.springframework.modulith.test.ApplicationModuleTest;
import org.springframework.modulith.test.ApplicationModuleTest.BootstrapMode;
import org.springframework.modulith.test.Scenario;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
// Boot only the orders module. Inventory is not loaded, and orders doesn't need it.
@ApplicationModuleTest(mode = BootstrapMode.STANDALONE)
class OrderModuleTests {
// A neighbouring module that orders still calls directly. Mock it because
// standalone mode leaves it out of the context.
@MockitoBean CustomerDirectory customers;
@Autowired OrderManagement orders;
@Test
void completingAnOrderPublishesEvent(Scenario scenario) {
scenario.stimulate(() -> orders.complete("order-42"))
.andWaitForEventOfType(OrderCompleted.class)
.matching(event -> event.orderId().equals("order-42"))
.toArrive(); // assert the outcome by its event, not by inventory's state
}
}
The inventory module consumes OrderCompleted through @ApplicationModuleListener, and the orders module is tested in standalone bootstrap mode, with a mocked neighbour and a Scenario assertion that waits for the published event.
When should you avoid Spring Modulith, and what are the alternatives?
Spring Modulith's verification is static analysis built on ArchUnit. It inspects type references in compiled classes, so it cannot see dependencies that never appear as types:
- Reflection.
- String-based bean lookups such as fetching a bean by name from the context.
- Two modules reading and writing the same database tables.
- Coupling through a shared schema, where one module's migration breaks another module's queries.
A green verify() run means no illegal type references were found. It does not mean the modules are isolated. If modules share tables today, the tool will report clean boundaries while the real coupling sits in SQL.
The package-equals-module convention also fights layer-first layouts. If your direct sub-packages are controller, service and repository, each layer becomes an "application module." Every feature then crosses every boundary, and the verification output becomes noise. Getting useful results means first restructuring into feature packages. On a large codebase that move is the real cost.
| Option | Enforcement point | Granularity | Restructuring cost | Runtime isolation | Operational overhead |
|---|---|---|---|---|---|
| Plain ArchUnit rules | Test time | Any package or class rule you write | Low; rules fit the current layout | None | Low; you maintain the rules |
| Multi-module Maven/Gradle | Compile time | Build artifact | Medium to high | None; one classpath | Low to moderate build complexity |
| Java Platform Module System | Compile time and runtime | Exported packages | High; affects libraries and reflection | Strong encapsulation, same process | Moderate tooling friction |
| Separate services | Network boundary | Service | Very high | Process and data isolation | High: deployment, observability, distributed failures |
| Doing nothing | None | None | None | None | None upfront; boundaries erode over time |
How does Spring Modulith affect development cost and save engineering time on a legacy codebase?
The costs come first. Legacy codebases are rarely organised by business capability, so the initial work is moving classes into top-level packages that match real modules. The first verify() run on such a codebase often reports dozens of violations at once, and a team that tries to clear them in one push can stall feature work for weeks. Events add operational load too: persisted publications need monitoring, retries and cleanup of completed entries.
| Area | Upfront cost | Ongoing saving |
|---|---|---|
| Boundary enforcement | Restructuring packages, fixing violations | Automated checks replace manual review of dependencies |
| Documentation | Configuring generation | Diagrams generated from code, never stale |
| Testing | Splitting test setup per module | Module tests bootstrap less context, run faster, fail locally |
| Events | Publication registry operations | Fewer direct cross-module calls to untangle later |
Illustrative estimate (assumed numbers, not a benchmark): monthly review saving = PRs per month × minutes of manual boundary review per PR. Assume 120 PRs and 10 minutes each, which gives 1,200 minutes, or about 20 hours a month. If restructuring costs 80 hours, payback = 80 ÷ 20 = 4 months. Substitute your own figures.
A staged migration order
- Inspect: print the detected modules and accept the current state as a baseline.
- Fix cycles: these block every later step.
- Hide internals: move implementation classes into sub-packages.
- Tighten
allowedDependenciesmodule by module.
Fix the violations a few at a time and keep the rules strict. If you loosen a rule to get a green build, the violation is still there and nothing will tell you about it again.
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.