0Pricing
Spring Boot 4 Complete Guide · 课时

应用模块与边界验证

使用 Spring Modulith 的结构验证和文档功能定义并强制执行模块边界。

应用模块与边界验证 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Module Boundaries Matter

A Spring Boot monolith tends to rot: any class can @Autowired any other, and over time everything depends on everything. Spring Modulith brings discipline by treating top-level packages under your main application package as application modules.

  • Each direct sub-package of the main package is one module.
  • Code inside a module's root package and a special api sub-package is public.
  • All other nested packages are internal and may not be referenced from other modules.

This lets you keep a single deployable while enforcing the boundaries you would get from microservices.

A Modular Package Layout

Consider an e-commerce app with the main class in com.shop. Each business concern becomes a direct sub-package. Spring Modulith infers the modules order, inventory, and notification from this structure alone — no XML, no annotations required.

Classes directly in com.shop.order are the module's public API; classes in com.shop.order.internal are hidden from other modules.

com.shop
├── ShopApplication.java
├── order
│   ├── OrderService.java          // public API
│   └── internal
│       └── OrderRepository.java   // internal
├── inventory
│   ├── InventoryService.java
│   └── internal
│       └── StockLevel.java
└── notification
    └── NotificationService.java

Adding the Modulith Dependency

Spring Modulith ships as a BOM plus a set of starters. For boundary verification and documentation you need spring-modulith-starter-core on the test classpath (and usually the test starter).

  • The BOM aligns all Modulith artifact versions with your Spring Boot version.
  • spring-modulith-starter-test brings the ApplicationModules verification API into the test scope.
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.modulith</groupId>
      <artifactId>spring-modulith-bom</artifactId>
      <version>1.4.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

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

Bootstrapping the Module Model

The entry point for everything is ApplicationModules.of(...). You pass it your main application class; Modulith scans the package structure and builds an in-memory model of every module and its allowed dependencies.

Calling verify() on that model fails fast if any module reaches into another module's internals or forms an illegal cyclic dependency.

import org.springframework.modulith.core.ApplicationModules;

class ModularityTests {

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

    @org.junit.jupiter.api.Test
    void verifiesModularStructure() {
        modules.verify();
    }
}

What verify() Actually Checks

A single call to verify() enforces several structural rules at once:

  • No internal access: a module may only depend on another module's public types (root package or api package), never its internal sub-packages.
  • No cycles: module dependencies must form a directed acyclic graph; A→B→A fails the build.
  • Declared dependencies only: if a module restricts its allowed dependencies with @ApplicationModule(allowedDependencies = ...), any undeclared dependency is rejected.

Run it as a normal JUnit test so violations break CI before they ever ship.

Restricting Allowed Dependencies

By default a module may depend on any other module's public API. To tighten that, place a package-info.java in the module's root package and annotate it with @ApplicationModule.

Here the order module is allowed to use only inventory. If someone later wires NotificationService into the order module, verify() fails immediately.

@org.springframework.modulith.ApplicationModule(
    allowedDependencies = { "inventory" }
)
package com.shop.order;

import org.springframework.modulith.ApplicationModule;

Named Interfaces for Selective Exposure

Sometimes a module needs to expose a second public surface beyond its root package. A named interface marks an extra package as public and lets other modules target it explicitly.

Annotate the package with @NamedInterface("spi"); then a consumer can declare a dependency on order :: spi rather than the whole module.

// com/shop/order/spi/package-info.java
@org.springframework.modulith.NamedInterface("spi")
package com.shop.order.spi;

import org.springframework.modulith.NamedInterface;

// Consumer module restricts itself to that named interface
@org.springframework.modulith.ApplicationModule(
    allowedDependencies = { "order :: spi" }
)
package com.shop.billing;

Decoupling with Application Events

The cleanest way to keep modules independent is to avoid direct service calls altogether. Instead of injecting InventoryService into the order module, publish a Spring ApplicationEventPublisher event and let inventory listen.

This inverts the dependency: order no longer needs to know inventory exists, which keeps the verified dependency graph small and acyclic.

@org.springframework.stereotype.Service
class OrderService {

    private final org.springframework.context.ApplicationEventPublisher events;

    OrderService(org.springframework.context.ApplicationEventPublisher events) {
        this.events = events;
    }

    void placeOrder(String sku, int qty) {
        // ... persist order ...
        events.publishEvent(new OrderPlaced(sku, qty));
    }
}

record OrderPlaced(String sku, int qty) {}

Listening Across Modules

The inventory module consumes the event without any compile-time link back to order — it only depends on the published event type. Spring Modulith encourages @ApplicationModuleListener, which combines @Async, @Transactional(propagation = REQUIRES_NEW), and @TransactionalEventListener so the listener runs in its own transaction after the publisher commits.

@org.springframework.stereotype.Component
class InventoryEventHandler {

    @org.springframework.modulith.events.ApplicationModuleListener
    void on(OrderPlaced event) {
        // runs async, in a fresh transaction, after commit
        decrementStock(event.sku(), event.qty());
    }

    private void decrementStock(String sku, int qty) { /* ... */ }
}

Generating Living Documentation

The same module model can render documentation. Documenter produces C4-style component diagrams (PlantUML) and an Asciidoctor module canvas describing each module's dependencies, exposed types, and events.

Because the diagrams are derived from real code during the test run, they never drift out of date — regenerating is just re-running the test.

import org.springframework.modulith.docs.Documenter;

@org.junit.jupiter.api.Test
void writeDocumentation() {
    var modules = ApplicationModules.of(ShopApplication.class);
    new Documenter(modules)
            .writeModulesAsPlantUml()      // overview diagram
            .writeIndividualModulesAsPlantUml()
            .writeModuleCanvases();        // target/modulith-docs
}

A Standalone Cycle Check

The boundary idea — reject dependency cycles — is simple enough to model in plain Java. This runnable program builds a tiny module graph and reports whether a cycle exists, mirroring what verify() does for real modules.

import java.util.*;

public class CycleCheck {
    static Map<String, List<String>> graph = new HashMap<>();

    static void dependsOn(String a, String b) {
        graph.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
    }

    static boolean hasCycle(String node, Set<String> stack, Set<String> seen) {
        if (stack.contains(node)) return true;
        if (seen.contains(node)) return false;
        seen.add(node);
        stack.add(node);
        for (String next : graph.getOrDefault(node, List.of()))
            if (hasCycle(next, stack, seen)) return true;
        stack.remove(node);
        return false;
    }

    public static void main(String[] args) {
        dependsOn("order", "inventory");
        dependsOn("inventory", "order"); // illegal cycle
        boolean cyclic = false;
        for (String m : graph.keySet())
            cyclic |= hasCycle(m, new HashSet<>(), new HashSet<>());
        System.out.println("Cycle detected: " + cyclic);
    }
}

Quick Check

You annotate the order module with @ApplicationModule(allowedDependencies = { "inventory" }). A new commit injects NotificationService (from the notification module) into a bean inside order. What happens?

Recap

You learned how Spring Modulith turns a Spring Boot monolith into a set of verified modules:

  • Modules are the direct sub-packages of your main application package; root and api/named-interface packages are public, the rest internal.
  • ApplicationModules.of(App.class).verify() enforces no internal access, no cycles, and declared-only dependencies as a JUnit test.
  • @ApplicationModule(allowedDependencies = ...) tightens the graph; @NamedInterface exposes extra public surfaces selectively.
  • Prefer application events with @ApplicationModuleListener to decouple modules instead of direct service calls.
  • Documenter generates always-current PlantUML diagrams and module canvases from the same model.

常见问题解答

「应用模块与边界验证」课时是免费的吗?

是的 — 「应用模块与边界验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。

「应用模块与边界验证」这节课中我会学到什么?

使用 Spring Modulith 的结构验证和文档功能定义并强制执行模块边界。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Complete Guide 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「应用模块与边界验证」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?

能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 应用模块与边界验证
  2. 应用内部事件与监听器
  3. 事务型事件发布与发件箱
  4. 模块集成测试与场景
← 返回 Spring Boot 4 Complete Guide