애플리케이션 모듈과 경계 검증
Spring Modulith의 구조 검증 및 문서화 기능으로 모듈 경계를 정의하고 적용합니다.
애플리케이션 모듈과 경계 검증은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
apisub-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.javaAdding 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-testbrings theApplicationModulesverification 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
apipackage), 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;@NamedInterfaceexposes extra public surfaces selectively.- Prefer application events with
@ApplicationModuleListenerto decouple modules instead of direct service calls. Documentergenerates always-current PlantUML diagrams and module canvases from the same model.
자주 묻는 질문
“애플리케이션 모듈과 경계 검증” 강의는 무료인가요?
네 — “애플리케이션 모듈과 경계 검증” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“애플리케이션 모듈과 경계 검증”에서 뭘 배우나요?
Spring Modulith의 구조 검증 및 문서화 기능으로 모듈 경계를 정의하고 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“애플리케이션 모듈과 경계 검증” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 애플리케이션 모듈과 경계 검증
- 애플리케이션 내부 이벤트와 리스너
- 트랜잭션 이벤트 발행과 아웃박스
- 모듈 통합 테스트와 시나리오