What is Spring Modulith and how does it derive application modules?
Spring Modulith is a Spring project for building a modular monolith in Java: one Spring Boot deployable whose business domains are kept apart by enforced boundaries instead of by network calls. It is aimed at teams that run a single application containing several domains (orders, inventory, billing) and want those domains to stay separable without moving to microservices.
Spring Modulith derives application modules from package structure. Each direct sub-package of the package that holds your @SpringBootApplication class becomes one module. Types in a module's base package form its public API. Types in nested packages are internal, and other modules must not reference them.
com.example.shop
├── ShopApplication (main class, defines the root)
├── orders module: orders
│ ├── OrderService [API]
│ ├── OrderCreated [API]
│ └── internal
│ ├── OrderRepository [internal]
│ └── OrderEntity [internal]
├── inventory module: inventory
│ ├── InventoryService [API]
│ └── persistence
│ └── StockLevel [internal]
└── shared module: shared
└── Money [API]
This convention works because Java's own visibility rules do not cover the case. A public class in orders.internal is visible to every package, so the compiler cannot stop inventory from importing OrderRepository. Spring Modulith supplies the missing rule: a module exposes its top-level package and hides everything below it.
The package layout only describes intent. The boundary is enforced by an executable verification test that fails the build when code crosses a boundary. The rest of this article treats that test as a CI contract.
com.example.shop (root = package of @SpringBootApplication ShopApplication)
+------------------------+ +------------------------+ +----------------+
| module: orders | | module: inventory | | module: shared |
|------------------------| |------------------------| |----------------|
| [API] OrderService |<-ok| [API] InventoryService |-ok>| [API] Money |
| [API] OrderCreated | | | | |
| +--------------------+ | | +--------------------+ | +----------------+
| | internal | |<-X-| | persistence | |
| | OrderRepository | | | | StockLevel | |
| | OrderEntity | | | +--------------------+ |
| +--------------------+ | | |
+------------------------+ +------------------------+
| |
+--------------+---------------+
v
+----------------------------------------------------------+
| Verification test, run in CI on every build |
| ApplicationModules.of(ShopApplication.class).verify() |
| any <-X- dependency => test fails => build fails |
+----------------------------------------------------------+
<-ok allowed: reference to another module's base package (API)
<-X- violation: reference into a nested (internal) package
Each direct sub-package of com.example.shop becomes a module. Types in a module's base package are its public API, and nested packages such as internal and persistence are hidden. The verification test fails the build when one module references another module's internal types.
How do you write a module verification test that runs on every build?
The test is an ordinary JUnit class with a single test method. It needs no @SpringBootTest, no application context, and no database. Inside the method, call ApplicationModules.of(Application.class), where Application is your @SpringBootApplication class. This builds the module model by analysing compiled bytecode from that class's package downward. Then call verify() on the result. If any rule is violated, verify() throws an exception, so the test fails and the build fails with it.
Because no beans are created and no ports are opened, the test runs in about the time it takes to import and scan your classes. That makes it cheap enough to run on every commit alongside your unit tests, not only in a nightly or integration stage. A boundary violation becomes a red build within seconds of the push. Otherwise it would surface weeks later as a review argument or as a coupling that blocks a refactor.
Inspecting the detected model
ApplicationModules is iterable, so a second test can loop over it and print each ApplicationModule. The printed output lists each module's name, base package, and the types it exposes. Check this output early, especially when adopting Spring Modulith. It shows whether the tool sees the same modules you intended, before you debug a verification failure that is really a package-layout mistake.
Diagrams for review
Pass the same ApplicationModules instance to a Documenter and call writeModulesAsPlantUml() or writeIndividualModulesAsPlantUml(). The diagrams are written to the build output directory. If you publish them as CI artifacts, reviewers can see a change in module dependencies without reading every import.
package com.example.shop;
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
import org.springframework.modulith.docs.Documenter;
// Plain JUnit test: no @SpringBootTest, so no context, beans or database.
class ModularityTests {
// Build the model once from compiled bytecode under Application's package.
static final ApplicationModules modules = ApplicationModules.of(Application.class);
@Test
void verifiesModularStructure() {
// Throws if any module boundary rule is violated, failing the build.
modules.verify();
}
@Test
void printsDetectedModules() {
// Check that the detected modules match the intended package layout.
modules.forEach(System.out::println);
}
@Test
void writesDocumentation() {
// Writes PlantUML diagrams to the build output directory
// so CI can publish them as artifacts for reviewers.
new Documenter(modules)
.writeModulesAsPlantUml()
.writeIndividualModulesAsPlantUml();
}
}
A context-free JUnit test class that verifies module boundaries with ApplicationModules.verify(), prints the detected module model, and generates PlantUML diagrams with Documenter for code review.
What does verify() check, and what does a failure look like?
verify() enforces two rules, and both come from the package structure it has already derived.
Rule 1: no cycles between modules
Suppose orders.OrderService calls inventory.InventoryService.reserve(), and InventoryService later calls back into OrderService to mark an order as backordered. Each call might look reasonable in its own pull request. Together they form a cycle: neither module can be understood, tested or extracted without the other. The verification fails and reports the cycle as a chain of modules, with the types and dependencies that create each edge.
Rule 2: no access to another module's internals
By default, only types in a module's base package form its API. If orders imports inventory.internal.StockRepository, it now depends on how inventory stores stock rather than on what inventory offers. The failure names the source type, the target type and the module that owns the target. Fix it by calling a public inventory type, or by exposing the type deliberately (covered in the next section).
Each report lists every violation it finds, so one run can show several problems.
What it cannot see
The analysis reads bytecode and package names. Any coupling that does not appear as a type reference is invisible to it:
| Coupling path | Detected by verify() |
|---|---|
| Direct type reference across modules | Yes |
| Import of another module's internal package | Yes |
| Two modules reading or writing the same table | No |
Reflection or getBean("name") lookups |
No |
| Shared configuration properties | No |
A shared module that every other module depends on |
No (it is not a cycle) |
A shared module that keeps growing is a design problem, even though the build passes. Treat these blind spots as review checklist items. A green build does not cover them.
// --- orders/OrderService.java -----------------------------------
package com.example.shop.orders;
import com.example.shop.inventory.InventoryService;
import com.example.shop.inventory.internal.StockRepository; // Rule 2: internal type of another module
@org.springframework.stereotype.Service
public class OrderService {
private InventoryService inventory; // edge: orders -> inventory
private StockRepository stock; // bypasses inventory's API (injection omitted)
public void place(String orderId, String sku) {
inventory.reserve(orderId, sku);
}
public void markBackordered(String orderId) { /* ... */ }
}
// --- inventory/InventoryService.java -----------------------------
package com.example.shop.inventory;
import com.example.shop.orders.OrderService; // Rule 1: edge back to orders closes the cycle
@org.springframework.stereotype.Service
public class InventoryService {
private OrderService orders; // edge: inventory -> orders (injection omitted)
public void reserve(String orderId, String sku) {
// Out of stock: call back into orders. Looks harmless in isolation.
orders.markBackordered(orderId);
}
}
// --- src/test/java/.../ModularityTests.java ----------------------
class ModularityTests {
@org.junit.jupiter.api.Test
void verifiesModuleBoundaries() {
// Derives modules from packages under ShopApplication and fails the build,
// reporting both the orders <-> inventory cycle and the internal access.
org.springframework.modulith.core.ApplicationModules.of(ShopApplication.class).verify();
}
}
Two classes that together break both rules (a cycle between orders and inventory, and orders importing inventory.internal.StockRepository), plus the one-line test that makes verify() fail the build on both.
How do named interfaces and allowedDependencies encode design intent?
By default, Spring Modulith treats only a module's base package as its public API. Every sub-package is internal, and a reference to it from another module fails verification. Two annotations let you override that default deliberately.
Named interfaces: widening the surface on purpose
When a sub-package such as payment.spi or order.dto really is meant for other modules, annotate it in its package-info.java with @NamedInterface("spi"). This exposes that package under a name, and nothing else in the module. The annotation sits next to the code it governs, so the decision to publish a contract shows up as a visible line in a diff.
allowedDependencies: narrowing what a module may use
On the module's base package-info.java, @ApplicationModule(allowedDependencies = { "inventory", "payment :: spi" }) limits the module to those targets. A bare module name permits that module's base package. The module :: interface form permits only the named interface. Any other dependency, including one that is technically public, fails verify(). This turns "orders should only talk to payment through its SPI" from a wiki note into a check that runs on every build.
The drift problem
This metadata only helps if someone looks at it. When a build goes red and the quickest fix is to add "billing" to the list or annotate another package, the annotations end up recording whatever the code already does, and they stop expressing intent. Treat edits to package-info.java as architecture changes. Route them to an owner through CODEOWNERS or an equivalent review rule, and require a sentence in the pull request explaining why the boundary moved.
// File: src/main/java/com/example/shop/payment/spi/package-info.java
// Deliberately publish payment's SPI sub-package to other modules.
// Without this, everything below com.example.shop.payment is internal.
@org.springframework.modulith.NamedInterface("spi")
package com.example.shop.payment.spi;
// ------------------------------------------------------------------
// File: src/main/java/com/example/shop/order/package-info.java
// Declare which modules 'order' may depend on. Anything not listed
// fails ApplicationModules.verify(), even if it is otherwise public.
@org.springframework.modulith.ApplicationModule(
allowedDependencies = {
"inventory", // base package (default public API) of inventory
"payment :: spi" // only payment's named interface "spi", not its base API
}
)
package com.example.shop.order;
// Review note: changes to either file move a module boundary.
// Route them to the architecture owner (e.g. via CODEOWNERS) and
// explain in the pull request why the boundary changed.
Two package-info.java files: one uses @NamedInterface to expose payment's SPI sub-package, the other uses @ApplicationModule(allowedDependencies) to limit order to inventory's base API and the payment :: spi named interface.
When should you use application events to break module cycles?
Suppose orders calls InventoryService.reserve() and inventory reads order data back from orders. verify() reports a cycle. To break it, orders publishes an OrderPlaced event through ApplicationEventPublisher, and inventory handles it in an event listener. The direction now runs one way. inventory depends on the event type that orders exposes, and orders no longer references inventory at all. The static cycle is gone, and the build passes.
The coupling did not disappear. It moved from compile time to runtime. Reading OrderService no longer tells you that placing an order reserves stock, so tracing the flow means searching for listeners. The structure test also leaves several questions open:
- Transaction scope. Does the listener run inside the publisher's transaction, after commit, or asynchronously? A plain
@EventListenerruns synchronously in the same transaction. A transactional listener that runs after commit can fail after the order is already saved. - Delivery. Is delivery guaranteed if the process crashes between commit and handling? Spring Modulith's event publication registry targets this case, but only if you configure it. Even then, your handlers need to be idempotent.
- Failure semantics. Should a failed reservation reject the order? If it should, an event is the wrong tool.
That last question is the useful test. If the caller needs the result to continue, the dependency is real, and an event only hides it. In that situation the cycle usually means a responsibility sits in the wrong module. Move the shared logic into the module that owns the data, or extract it into a lower-level module that both sides depend on. Use an event when the publisher can complete its own work without knowing who reacts or whether anyone does.
How do you introduce module verification into an existing codebase?
Most existing Spring Boot applications are organised by technical layer, with top-level controller, service and repository packages. Spring Modulith treats each direct sub-package of the main application package as a module, so a layered layout produces three "modules" that all depend on each other and tells you nothing useful. The first step is to regroup classes into domain packages such as orders, billing and inventory. This is mostly mechanical: IDE move refactorings handle it, but the diff touches nearly every file, so land it as its own change with no behaviour changes mixed in.
Next, build the module model and list the current violations without failing the build. Fix cycles first. A cycle means two modules cannot be understood or tested apart, and breaking it often removes several internal-access violations along the way. Then work through the remaining access to non-exposed types. Make verify() a required CI gate only once this backlog is empty. A hard gate on day one blocks unrelated work, and a test that blocks unrelated work tends to get disabled.
The cost is real. There is the upfront refactor, plus ongoing upkeep of named interfaces and allowed dependencies as the design changes. What you get back is less review effort spent spotting accidental coupling, and less time spent untangling modules later.
Once modules are clean, @ApplicationModuleTest bootstraps a single module's package. You can choose to include its dependencies or mock them. This shows that a module works in isolation, but it only checks the module under test. Keep verify() as well, because it is the one check that covers the dependencies between all modules.
When should you avoid Spring Modulith, and what are the alternatives?
Spring Modulith suits a team with one deployable that already holds several business domains, such as orders, billing and inventory, and wants those boundaries to stay in place. It may later split into services, or it may never need to. The boundaries are checked on every build, but moving a class between modules is still a normal IDE refactoring inside one source tree.
Skip it in three cases. A very small application has no boundaries worth defending, so the verification test adds ceremony without catching anything. Code that is not built on Spring gets little from it, because module detection and event handling assume a Spring application. Teams that need independent deployment, scaling or failure isolation need more than it offers. Modules still share one JVM, one release cycle and usually one database, so a memory leak in one module or a slow migration in another affects all of them.
| Approach | Enforcement strength | Refactoring cost | Runtime isolation |
|---|---|---|---|
| Package conventions plus code review | Weak: depends on reviewers noticing | Lowest | None |
| Hand-written architecture test rules | Strong, but only for rules someone wrote and maintains | Low | None |
| Spring Modulith | Strong, derived from package structure | Low | None |
| Separate Maven/Gradle subprojects | Strong at compile time: undeclared dependencies don't build | Medium: moving code means editing build files | None |
| Java Platform Module System | Strong, also enforced at run time for non-exported packages | Medium to high: module-info upkeep and reflection access |
Within one JVM only |
| Separate services | Strongest: the network is the boundary | Highest: API versioning and data ownership | Full |
These approaches can be combined. Build-level subprojects and Spring Modulith work together: the build blocks dependencies nobody declared, and verify() catches access to a module's internal packages, which the build cannot see.
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.