Skip to content
javahacks.dev
Microservices

How to Build a Modular Monolith With Spring Modulith

Structure a Spring Boot app into modules, verify the boundaries in a test, communicate through events and test one module at a time with Spring Modulith.

6 min read
Summarize in AI
Flat illustration of services connected around a gateway, with the Spring, Spring Boot and Redis logos.

A modular monolith is only modular if something stops the modules from collapsing into each other. Without enforcement, the ordering package imports billing internals within a month. Spring Modulith is that enforcement for Spring Boot, a small library that reads your package structure, verifies it and helps you test and document it. This post builds a two-module example. The reasoning behind the architecture is in microservices vs monolith, and the application setup in Spring Boot from first project to production.

Dependencies

pom.xmlXML
<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>

The Modulith BOM manages versions; use the release line that matches your Spring Boot version, listed in the project documentation.

The structure

Text
dev.javahacks.shop
  ShopApplication.java
  ordering/
    OrderService.java          public API of the ordering module
    OrderPlaced.java           public event
    internal/
      OrderRepository.java     internal, not visible to other modules
  billing/
    BillingEvents.java         listens to ordering's events

Each direct sub-package of dev.javahacks.shop is a module. By default the types in the module's root package are its API; anything in a nested package (ordering.internal) is internal. This is a convention, not a language feature, which is why a test enforces it.

Verify the boundaries

src/test/java/dev/javahacks/shop/ModularityTests.javajava
class ModularityTests {

    ApplicationModules modules = ApplicationModules.of(ShopApplication.class);

    @Test
    void verifiesModularStructure() {
        modules.verify();
    }
}

If billing imports ordering.internal.OrderRepository, the test fails with a message naming the offending dependency. The same applies to a cycle between modules. Run this test in CI and the structure stays honest. Generate documentation of the modules and their relationships as diagrams:

java
new Documenter(modules).writeModulesAsPlantUml();

Communicate through events

Direct calls from ordering to billing create a dependency from ordering to billing. Events invert it:

java
// ordering module
@Service
class OrderService {
    private final ApplicationEventPublisher events;
    OrderService(ApplicationEventPublisher events) { this.events = events; }

    @Transactional
    public void place(Order order) {
        // save the order
        events.publishEvent(new OrderPlaced(order.id(), order.totalCents()));
    }
}

// billing module
@Component
class BillingEvents {
    @ApplicationModuleListener
    void on(OrderPlaced event) {
        // create the invoice
    }
}

@ApplicationModuleListener is shorthand for an asynchronous, transactional listener that starts after the publishing transaction commits. The order is saved before billing reacts, and a failure in billing does not roll back the order. Billing now depends on ordering's event type and ordering knows nothing about billing.

Do not lose events

Because the listener runs after commit, a crash between commit and handling would lose the event. The event publication registry stores events in the database before delivery and marks them completed afterwards. Add the JDBC starter (spring-modulith-starter-jdbc) and an events table, and incomplete publications can be resubmitted on restart. This gives at-least-once delivery, so make listeners idempotent, as in idempotent endpoints.

Test one module

java
@ApplicationModuleTest
class BillingModuleTests {

    @Test
    void createsInvoiceWhenOrderPlaced(Scenario scenario) {
        scenario.publish(new OrderPlaced("o-1", 2_490))
                .andWaitForStateChange(() -> invoices.findByOrderId("o-1"))
                .andVerify(invoice -> assertThat(invoice).isPresent());
    }
}

@ApplicationModuleTest starts only the module under test with its declared dependencies, so tests are quick and exercise the boundary. Other modules' beans can be mocked.

Splitting later

The boundaries are the seams. A module with a public API and events can become a service by replacing the in-process call with an HTTP or messaging client and moving its tables. The next step is described in splitting a monolith.

State a module's allowed dependencies

By default any module may depend on any other module's public API, which verifies fine and lets a cycle grow by one import at a time. Declare the allowed dependencies in the module's package-info.java, and verification fails the moment a new arrow appears. For a shop with order, inventory and catalog modules:

src/main/java/dev/javahacks/shop/order/package-info.javajava
@ApplicationModule(
    displayName = "Order management",
    allowedDependencies = {"catalog", "inventory :: api"}
)
package dev.javahacks.shop.order;

import org.springframework.modulith.ApplicationModule;
src/main/java/dev/javahacks/shop/inventory/api/package-info.javajava
@NamedInterface("api")
package dev.javahacks.shop.inventory.api;

import org.springframework.modulith.NamedInterface;

The inventory :: api form lets order use only the types in the named interface api, not the whole of inventory's top-level package. Inventory can keep a second exposed surface for another consumer without widening this one. Any other import from order into inventory, or an import into payment that is not listed, now fails verify() in the test from the previous section with a message naming the module and the offending type.

Document the structure from the code

A diagram that is drawn by hand is wrong within a month. The Documenter writes component diagrams from the actual module graph, and the build can regenerate them.

java
class DocumentationTests {

    ApplicationModules modules = ApplicationModules.of(Application.class);

    @Test
    void writeDocumentation() {
        new Documenter(modules)
                .writeModulesAsPlantUml()
                .writeIndividualModulesAsPlantUml()
                .writeModuleCanvases();
    }
}

The output lands under target/spring-modulith-docs: a PlantUML file for the whole system, one per module, and a canvas per module that lists its exposed types, the events it publishes and listens to, and the beans it owns. Commit the diagram into the repository's docs, or publish the canvases from CI, so a reviewer can see whether a pull request changed the shape of the system.

Make the listener transactional on its own

A module reacting to another's event should not share its transaction. If the inventory listener runs inside the order transaction and throws, the order rolls back for a reason that belongs to a different module. @ApplicationModuleListener is shorthand for an asynchronous, transactional listener that runs after the publisher commits and opens a new transaction.

java
@Component
class InventoryListener {

    private final StockService stock;

    InventoryListener(StockService stock) { this.stock = stock; }

    @ApplicationModuleListener
    void on(OrderPlaced event) {
        stock.reserve(event.orderId(), event.lines());
    }
}

The event type, OrderPlaced, lives in the order module's exposed package, so the dependency points from inventory to order's published events and not the other way. If the listener fails, the order is already committed and the failure is an inventory problem to retry, which matches the behaviour a later split into two services would have. That alignment is the reason to write it this way from the start.

Keep unprocessed events with the event publication registry

Events published inside a transaction are lost if the process dies between the commit and the listener. Add the JDBC starter for the registry and Modulith records each publication in a table, marks it completed when the listener returns, and lets you resubmit the incomplete ones at startup.

XML
<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-starter-jdbc</artifactId>
</dependency>
properties
spring.modulith.events.jdbc.schema-initialization.enabled=true
spring.modulith.events.republish-outstanding-events-on-restart=true

The registry is an outbox that lives in your own database, so no broker is required to get at-least-once delivery between modules. Because delivery can repeat, make each listener idempotent. When a module later becomes a service, the same events can be externalised to Kafka or RabbitMQ with the @Externalized annotation, and the listener code does not change.

Decide what a module owns in the database

A modular monolith keeps one database, and the discipline that matters is table ownership. Each module reads and writes its own tables, and reads another module's data through that module's API, not through a join. Prefix tables with the module name (order_line, inventory_stock) and forbid cross-module foreign keys in review. The first time a report needs a join across modules, build it as a read model fed by events. That rule, enforced early, is what makes the eventual extraction of a module a project of weeks and not of quarters.

Where this does not apply

Modulith checks package structure, not runtime behavior; modules still share a process and a database. For a team that has already split into services, it adds nothing. The Spring Modulith reference documentation and the event publication registry chapter are the primary sources.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.