Spring Modulith: Building Modular Monoliths with Spring Boot 4.2

Microservices are not the only way to build maintainable systems. A modular monolith keeps a single deployable application while enforcing clear module boundaries inside the codebase.

Spring Modulith provides the tools to build this architecture with Spring Boot. It helps you verify module dependencies, communicate through events, test modules independently, and generate documentation.

Table of Contents

What Is Spring Modulith?

Spring Modulith is a Spring project for building modular applications with Spring Boot. It treats each package directly beneath the main application package as an application module.

Modules expose a public API and hide internal implementation details. Spring Modulith verifies that modules do not depend on each other’s internals.

Core capabilities

  • Module structure verification.
  • Event-driven communication between modules.
  • Module-level integration testing.
  • Documentation generation.
  • Optional event publication persistence.

Spring Modulith 2.2 builds against Spring Boot 4.2 and Spring Framework 7.1, making it a natural fit for a Spring Boot 4.2 application.

Why a Modular Monolith?

A modular monolith offers many benefits of microservices without the operational overhead of distributed systems.

Benefits

  • Single deployment unit.
  • Simple local development.
  • No network calls between modules.
  • Strong transactional consistency where needed.
  • Clear boundaries that support future extraction.
  • Easier debugging and tracing.

Modular monolith vs microservices

Aspect Modular monolith Microservices
Deployment Single application Multiple services
Communication In-process method calls and events Network calls and messaging
Operational complexity Lower Higher
Module boundaries Enforced in code Enforced by service contracts
Independent scaling Limited Strong
Best for Small to medium teams and domains Large organizations with independent teams

A modular monolith is often the better starting point. You can extract modules into services later if scaling or team structure requires it.

Project Setup

Add Spring Modulith dependencies to your Spring Boot project.

Maven

<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>

Gradle

implementation 'org.springframework.modulith:spring-modulith-starter-core'
testImplementation 'org.springframework.modulith:spring-modulith-starter-test'

Optional: event publication persistence

If you want reliable event publication, add a persistence module for your database.

<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-starter-jpa</artifactId>
</dependency>

Defining Modules

Spring Modulith derives modules from the package structure. Each direct sub-package of the main application package becomes a module.

Example package structure

com.example.shop
├── ShopApplication.java
├── order
│   ├── Order.java
│   ├── OrderService.java
│   └── internal
│       └── OrderRepository.java
├── inventory
│   ├── InventoryService.java
│   └── internal
│       └── InventoryRepository.java
└── payment
    ├── PaymentService.java
    └── internal
        └── PaymentGateway.java

In this structure, order, inventory, and payment are application modules.

Module API and internals

Types in the module’s root package are part of its public API. Types in sub-packages, such as internal, are implementation details.

package com.example.shop.order;

public record Order(Long id, Long productId, int quantity) {
}
package com.example.shop.order.internal;

import com.example.shop.order.Order;
import org.springframework.stereotype.Repository;

@Repository
class OrderRepository {

    Order save(Order order) {
        return order;
    }
}

Other modules may use Order but should not depend on OrderRepository.

Named interfaces

You can explicitly define a module’s public API using @NamedInterface.

package com.example.shop.order;

import org.springframework.modulith.NamedInterface;

@NamedInterface("api")
public record OrderSummary(Long id, String status) {
}

Declaring a module

Use @ApplicationModule to declare module-level rules, such as allowed dependencies.

package com.example.shop.order;

import org.springframework.modulith.ApplicationModule;

@ApplicationModule(
    displayName = "Order Management",
    allowedDependencies = {"inventory", "payment"}
)
package com.example.shop.order;

Place this annotation in package-info.java.

Verifying Module Boundaries

Spring Modulith can verify that modules follow the intended dependency rules. This is one of its most valuable features.

Basic verification test

import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;

class ModularityTests {

    @Test
    void verifiesModuleStructure() {
        ApplicationModules modules =
            ApplicationModules.of(ShopApplication.class);

        modules.verify();
    }
}

If a module depends on another module’s internal type, the test fails with a clear violation message.

Example violation

Module 'order' depends on non-exposed type
com.example.shop.inventory.internal.InventoryRepository

Why verification matters

  • Prevents accidental coupling between modules.
  • Keeps module APIs intentional.
  • Makes future service extraction easier.
  • Documents architectural rules in code.
  • Catches boundary violations during CI.

Excluding infrastructure packages

Some packages, such as shared configuration or database migration code, may not represent business modules. Exclude them from verification.

import org.springframework.modulith.core.ApplicationModules;
import org.springframework.modulith.core.JavaClass;

ApplicationModules modules = ApplicationModules.of(
    ShopApplication.class,
    JavaClass.Predicates.resideInAPackage("com.example.shop.config")
);

modules.verify();

Module Communication with Events

Modules should communicate through events rather than direct calls to each other’s internals. Spring Modulith provides @ApplicationModuleListener for this purpose.

Publishing an event

package com.example.shop.order;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private final ApplicationEventPublisher events;
    private final OrderRepository orderRepository;

    public OrderService(
            ApplicationEventPublisher events,
            OrderRepository orderRepository) {
        this.events = events;
        this.orderRepository = orderRepository;
    }

    public Order placeOrder(Long productId, int quantity) {
        Order order = new Order(null, productId, quantity);
        Order saved = orderRepository.save(order);

        events.publishEvent(
            new OrderCompleted(saved.id(), saved.productId(), saved.quantity())
        );

        return saved;
    }
}

Defining the event

package com.example.shop.order;

public record OrderCompleted(
    Long orderId,
    Long productId,
    int quantity
) {
}

Listening in another module

package com.example.shop.inventory;

import com.example.shop.order.OrderCompleted;
import org.springframework.modulith.events.ApplicationModuleListener;
import org.springframework.stereotype.Component;

@Component
class InventoryManagement {

    @ApplicationModuleListener
    void on(OrderCompleted event) {
        // Reserve inventory for the completed order
    }
}

What @ApplicationModuleListener does

@ApplicationModuleListener combines several annotations into one:

  • @Async for asynchronous execution.
  • @Transactional(propagation = REQUIRES_NEW) for a new transaction.
  • @TransactionalEventListener for transaction-aware delivery.

This means the listener runs after the publishing transaction commits, in its own transaction.

Event flow

OrderService
    │
    ├── saves order
    ├── publishes OrderCompleted
    │
    ▼
Transaction commits
    │
    ▼
InventoryManagement.on(OrderCompleted)
    │
    └── reserves inventory

Event externalization

Spring Modulith can persist published events and deliver them to external systems. This supports reliable event-driven integration without losing events when a process crashes.

Testing Modules

Spring Modulith supports module-level integration tests through @ApplicationModuleTest.

Basic module test

import org.junit.jupiter.api.Test;
import org.springframework.modulith.test.ApplicationModuleTest;
import org.springframework.beans.factory.annotation.Autowired;

@ApplicationModuleTest
class OrderModuleTests {

    @Autowired
    private OrderService orderService;

    @Test
    void shouldPlaceOrder() {
        Order order = orderService.placeOrder(1L, 2);

        assertThat(order).isNotNull();
    }
}

@ApplicationModuleTest bootstraps only the module under test and its dependencies, making tests faster and more focused than a full application context.

Verifying published events

import org.junit.jupiter.api.Test;
import org.springframework.modulith.test.ApplicationModuleTest;
import org.springframework.modulith.test.PublishedEvents;

import static org.assertj.core.api.Assertions.assertThat;

@ApplicationModuleTest
class OrderEventTests {

    @Test
    void shouldPublishOrderCompletedEvent(
            OrderService orderService,
            PublishedEvents events) {

        Order order = orderService.placeOrder(1L, 2);

        assertThat(events)
            .contains(OrderCompleted.class)
            .matching(
                OrderCompleted::orderId,
                order.id()
            );
    }
}

Testing event listeners

@ApplicationModuleTest
class InventoryModuleTests {

    @Test
    void shouldReserveInventoryOnOrderCompleted(
            InventoryService inventoryService,
            PublishedEvents events) {

        // Trigger the event through the order module
        // and assert inventory state
    }
}

Generating Documentation

Spring Modulith can generate documentation from the module model. This is useful for architecture reviews and onboarding.

Generate documentation snippets

import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
import org.springframework.modulith.docs.Documenter;

class DocumentationTests {

    @Test
    void writeDocumentationSnippets() {
        ApplicationModules modules =
            ApplicationModules.of(ShopApplication.class).verify();

        new Documenter(modules)
            .writeModulesAsPlantUml()
            .writeIndividualModulesAsPlantUml();
    }
}

What gets generated

  • Module dependency diagrams.
  • Individual module diagrams.
  • Module component documentation.
  • PlantUML and Asciidoctor output.

The generated diagrams make architectural boundaries visible to the whole team.

Best Practices

  • Keep modules aligned with business capabilities, not technical layers.
  • Expose a small, intentional public API per module.
  • Put implementation details in internal sub-packages.
  • Use events for cross-module side effects.
  • Run module verification in CI.
  • Test modules independently with @ApplicationModuleTest.
  • Generate and review module documentation regularly.
  • Avoid shared “utility” modules that become dumping grounds.

Common mistakes

  • Creating one module per technical layer instead of per business capability.
  • Exposing repositories or entities as public API.
  • Using direct calls between modules for side effects.
  • Ignoring verification failures instead of fixing boundaries.
  • Making every package a module without a clear domain model.

FAQs

What is Spring Modulith?

Spring Modulith is a Spring project for building modular monoliths with Spring Boot. It verifies module boundaries, supports event-driven communication, and generates documentation.

Is Spring Modulith a replacement for microservices?

No. It is an alternative architecture for applications that do not need independent deployment and scaling. Modules can be extracted into services later if needed.

How does Spring Modulith detect modules?

It treats each direct sub-package of the main application package as an application module.

What is @ApplicationModuleListener?

It is a shortcut annotation that combines asynchronous execution, a new transaction, and transaction-aware event handling.

How do I verify module boundaries?

Create an ApplicationModules instance and call verify() in a test. Run the test in CI to catch boundary violations.

Can Spring Modulith persist events?

Yes. With the appropriate persistence module, Spring Modulith can store published events and deliver them reliably to listeners or external systems.

Does Spring Modulith work with Spring Boot 4.2?

Yes. Spring Modulith 2.2 builds against Spring Boot 4.2 and Spring Framework 7.1.

When should I choose a modular monolith?

Choose it when you want clear boundaries without the operational complexity of microservices, especially for small to medium teams and domains.

Final Thoughts

Spring Modulith gives teams a practical path to modular architecture without committing to distributed systems. It enforces boundaries, encourages event-driven communication, and makes module structure visible through tests and documentation.

Start with a small set of business-capability modules, verify boundaries in CI, and use events for cross-module side effects. If a module later needs independent scaling, its boundaries make extraction far easier.

Comments