Add order-fulfillment module: Spring Modulith 2.1 boundary enforcement, events, generated docs

This commit is contained in:
2026-10-03 18:36:16 +00:00
commit 725d766e7a
36 changed files with 2975 additions and 0 deletions
+1014
View File
File diff suppressed because it is too large Load Diff
+813
View File
@@ -0,0 +1,813 @@
<!-- wp:html -->
<p>Every modular monolith starts the same way: a clean diagram, a handful of packages
named after the business, and a promise that <code>order</code> will not reach into
<code>inventory</code>&#8217;s business. Six months and four developers later, somebody
adds exactly that reach &#8212; a repository field, a quick read, &#8220;it&#8217;s all
one database anyway&#8221; &#8212; and nothing stops them. The code compiles. The tests
that exist still pass. The diagram is now a lie, and nobody finds out until the day
someone tries to split the monolith and discovers the boundaries were never real.</p>
<p>Spring Modulith is Spring&#8217;s answer to that specific failure: not a framework
for writing microservices-shaped code inside one deployable, but a verification tool
that turns your package structure into a contract a test can enforce. This post builds
a small, real order-fulfillment app with four modules, breaks the boundary between two
of them on purpose, watches the actual test failure, fixes it, and then shows that the
"fix" most people reach for first &#8212; routing the call through the public API
instead of the internals &#8212; still fails, for a reason that matters more than the
original mistake.</p>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>Versions used in this post, verified against Maven Central&#8217;s maven-metadata.xml, not the project&#8217;s own &lt;release&gt; tag (which currently points at the 2.2.0-M2 milestone &#8212; a GA pointer that has been wrong before is not a GA pointer you can trust).</strong> Spring Boot 4.1.1 &#183; Spring Modulith 2.1.1 (2.1 went GA 11 June 2026; 2.1.1 is the current patch; 2.2 exists only as milestones as of this writing) &#183; JDK 25 LTS &#183; H2 2.4.240 for the demo database.</blockquote>
<!-- /wp:html -->
<!--more-->
<!-- wp:html -->
<h2>What a "module" is to Spring Modulith</h2>
<p>Spring Modulith does not introduce a new way to write Spring code. It looks at
packages you were probably going to create anyway and gives them meaning. The default
convention &#8212; and the one this post uses &#8212; is <strong>package by
feature</strong>: every direct sub-package of the package holding
<code>@SpringBootApplication</code> is a module. No XML, no registry, no annotation
required to declare one.</p>
<p>The demo app has four: <code>order</code>, <code>inventory</code>, <code>shipping</code>,
and <code>notification</code>, each a sub-package of
<code>com.ankurm.modulithdemo</code>. Inside each module, anything directly in the
module&#8217;s own package is that module&#8217;s <strong>public API</strong> &#8212;
fair game for other modules to depend on. Anything one level deeper, in an
<code>internal</code> sub-package, is exactly that: internal, and off-limits to
everyone else, regardless of whether the Java compiler marks it <code>public</code>.
Java&#8217;s own visibility modifiers stop at the package; Spring Modulith is the thing
that enforces the rest.</p>
<figure role="img" aria-label="Four modules: Inventory and Notification both depend on Order by listening for its events; Shipping depends on Inventory the same way; Order depends on nothing.">
<svg viewBox="0 0 740 320" xmlns="http://www.w3.org/2000/svg">
<style>
.t{font:600 15px sans-serif;fill:#2b2f38}
.h{font:600 13px sans-serif;fill:#2b2f38}
.c{font:12px sans-serif;fill:#5b6270}
.m{font:12px monospace;fill:#5b6270}
.lbl{font:11px sans-serif;fill:#5b6270}
</style>
<rect x="0" y="0" width="740" height="320" fill="#ffffff"/>
<text x="20" y="28" class="t">Module dependency graph (as generated by Documenter)</text>
<rect x="300" y="60" width="140" height="56" rx="8" fill="#e8eefc" stroke="#5b7fc7"/>
<text x="370" y="93" class="h" text-anchor="middle">order</text>
<rect x="300" y="200" width="140" height="56" rx="8" fill="#e7f4ea" stroke="#4a9d63"/>
<text x="370" y="233" class="h" text-anchor="middle">inventory</text>
<rect x="80" y="200" width="140" height="56" rx="8" fill="#e7f4ea" stroke="#4a9d63"/>
<text x="150" y="233" class="h" text-anchor="middle">shipping</text>
<rect x="520" y="200" width="160" height="56" rx="8" fill="#e7f4ea" stroke="#4a9d63"/>
<text x="600" y="226" class="h" text-anchor="middle">notification</text>
<!-- inventory -> order -->
<line x1="370" y1="200" x2="370" y2="118" stroke="#4a9d63" stroke-width="2" marker-end="url(#arrow)"/>
<text x="378" y="160" class="lbl">listens to OrderPlaced</text>
<!-- shipping -> inventory -->
<line x1="190" y1="210" x2="300" y2="217" stroke="#4a9d63" stroke-width="2" marker-end="url(#arrow)"/>
<text x="190" y="200" class="lbl">listens to StockReserved</text>
<!-- notification -> order -->
<path d="M 600 200 C 600 120, 450 90, 440 88" fill="none" stroke="#4a9d63" stroke-width="2" marker-end="url(#arrow)"/>
<text x="460" y="60" class="lbl">listens to OrderPlaced</text>
<!-- notification -> shipping -->
<path d="M 520 225 C 350 290, 240 260, 222 232" fill="none" stroke="#4a9d63" stroke-width="2" marker-end="url(#arrow)"/>
<text x="330" y="300" class="lbl">listens to ShipmentScheduled</text>
<defs>
<marker id="arrow" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
<path d="M0,0 L8,4 L0,8 z" fill="#4a9d63"/>
</marker>
</defs>
<text x="20" y="300" class="c">order has zero outgoing arrows. Nothing it does depends on inventory, shipping, or notification &#8212; by design.</text>
</svg>
</figure>
<p>That diagram is not something I drew by hand and hoped matches the code. It is the
real output of Spring Modulith&#8217;s own <code>Documenter</code>, reading this
repository&#8217;s bytecode and generating a PlantUML component diagram and a
per-module canvas &#8212; see the accordion near the end of this post for the raw
PlantUML and the full captured transcript. Every arrow is a <code>"listens to"</code>
relationship the tool found by inspecting <code>@ApplicationModuleListener</code>
method parameters, not something I asserted.</p>
<p>Notice the direction. <code>inventory</code> and <code>notification</code> both
point at <code>order</code>, and <code>notification</code> also points at
<code>shipping</code>. <code>order</code> points at nothing. That is not an accident of
this particular app; it is the whole design goal, and it is the thing that gets broken
in the next section.</p>
<h2>The test that makes the diagram enforceable</h2>
<p>The diagram above is only worth anything if something fails the build the moment it
stops being true. That something is two lines:</p>
<pre><code class="language-java">class ModularityTests {
ApplicationModules modules = ApplicationModules.of(Application.class);
@Test
void verifiesModuleStructure() {
modules.verify();
}
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/test/java/com/ankurm/modulithdemo/ModularityTests.java">ModularityTests.java</a></p>
<p><code>ApplicationModules.of(Application.class)</code> scans the bytecode reachable
from the application&#8217;s main package and builds the module model described above.
<code>verify()</code> walks every type dependency it finds &#8212; constructor
parameters, fields, method bodies, the lot &#8212; and throws
<code>org.springframework.modulith.core.Violations</code>, a <code>RuntimeException</code>,
the moment one of them crosses a module boundary it should not. Put it in a JUnit test
and it becomes a build-breaking architecture check that runs on every commit, with zero
ArchUnit rules to hand-write.</p>
<p>The app itself needs nothing special to make this work. Here is the whole bootstrap
class:</p>
<pre><code class="language-java">@SpringBootApplication
@Modulithic(systemName = "Order Fulfillment")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/main/java/com/ankurm/modulithdemo/Application.java">Application.java</a>
&#8212; <code>@Modulithic</code> is optional (it names the system for the generated
documentation) but <code>ApplicationModules.of()</code> works with a plain
<code>@SpringBootApplication</code> class just as well.</p>
<p>The Maven coordinates for all of this are one BOM import and two starters &#8212;
one for the main app, one for the tests:</p>
<pre><code class="language-xml">&lt;dependencyManagement>
&lt;dependencies>
&lt;dependency>
&lt;groupId>org.springframework.modulith&lt;/groupId>
&lt;artifactId>spring-modulith-bom&lt;/artifactId>
&lt;version>2.1.1&lt;/version>
&lt;type>pom&lt;/type>
&lt;scope>import&lt;/scope>
&lt;/dependency>
&lt;/dependencies>
&lt;/dependencyManagement>
&lt;dependencies>
&lt;dependency>
&lt;groupId>org.springframework.modulith&lt;/groupId>
&lt;artifactId>spring-modulith-starter-jpa&lt;/artifactId>
&lt;/dependency>
&lt;dependency>
&lt;groupId>org.springframework.modulith&lt;/groupId>
&lt;artifactId>spring-modulith-starter-test&lt;/artifactId>
&lt;scope>test&lt;/scope>
&lt;/dependency>
&lt;/dependencies></code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/pom.xml">pom.xml</a></p>
<h2>Breaking it on purpose</h2>
<p>Here is the shortcut a real developer takes under real time pressure. Before placing
an order, <code>OrderManagement</code> wants to know whether there is enough stock.
The honest way is to ask <code>inventory</code>&#8217;s public API. The fast way, if you
already know the schema and you are in a hurry, is to inject
<code>inventory.internal.StockRepository</code> directly and query it yourself:</p>
<pre><code class="language-java">public class OrderManagement {
private final OrderRepository orders;
private final ApplicationEventPublisher events;
// the shortcut: read inventory's table directly instead of asking inventory
private final StockRepository stockShortcut;
public OrderManagement(OrderRepository orders,
ApplicationEventPublisher events,
StockRepository stockShortcut) {
this.orders = orders;
this.events = events;
this.stockShortcut = stockShortcut;
}
@Transactional
public Order placeOrder(String sku, int quantity) {
stockShortcut.findBySku(sku); // "it's all one database anyway"
var order = orders.save(new Order(sku, quantity, "PLACED"));
events.publishEvent(new OrderPlaced(order.getId(), order.getSku(), order.getQuantity()));
return order;
}
}</code></pre>
<p>This compiles. It runs. If you call the endpoint by hand, you will not see anything
wrong. The only thing standing between this code and production is the test from the
previous section &#8212; and here is exactly what it says when it runs against this
version of the code:</p>
<pre><code class="language-console">org.springframework.modulith.core.Violations:
- Cycle detected: Slice inventory ->
Slice order ->
Slice inventory
2. Dependencies of Slice order
- Field &lt;...OrderManagement.stockShortcut> has type &lt;...inventory.internal.StockRepository>
- Method &lt;...OrderManagement.placeOrder(String, int)> calls method
&lt;...inventory.internal.StockRepository.findBySku(String)>
- Module 'order' depends on non-exposed type
com.ankurm.modulithdemo.inventory.internal.StockRepository within module 'inventory'!
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 -- BUILD FAILURE</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/01-verify-violation-failed.txt">output/01-verify-violation-failed.txt</a></p>
<p>One field produced two separate violations in the same run, and they are worth
telling apart, because they have different fixes.</p>
<p>The second one &#8212; <code>"depends on non-exposed type"</code> &#8212; is the
one most people expect: <code>StockRepository</code> lives under
<code>inventory.internal</code>, and nothing outside <code>inventory</code> is allowed
to reference it, public interface or not.</p>
<p>The first one &#8212; <code>"Cycle detected: Slice inventory -&gt; Slice order
-&gt; Slice inventory"</code> &#8212; is the one that catches people out, and it is the
subject of the rest of this section. <code>inventory</code> already depends on
<code>order</code>: its <code>@ApplicationModuleListener</code> method takes
<code>OrderPlaced</code> as a parameter, and that is a real dependency edge as far as
Spring Modulith is concerned, identical in kind to a constructor argument. Adding a
field that points the other way &#8212; <code>order</code> depending on anything in
<code>inventory</code> &#8212; closes a two-module cycle, and Spring Modulith treats
the module graph as a strict DAG by default. A cycle fails verification even before the
tool asks whether the specific type you reached for happens to be internal.</p>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>The instinct to fix this by "going through the public API" is natural, and it is wrong here.</strong> Watch what happens next.</blockquote>
<p>The obvious-looking fix is to leave the field, but point it at
<code>InventoryManagement</code> &#8212; inventory&#8217;s real, intentional public
API &#8212; instead of the internal repository:</p>
<pre><code class="language-java">public class OrderManagement {
private final OrderRepository orders;
private final ApplicationEventPublisher events;
private final InventoryManagement inventory; // the real public API this time
public OrderManagement(OrderRepository orders,
ApplicationEventPublisher events,
InventoryManagement inventory) {
this.orders = orders;
this.events = events;
this.inventory = inventory;
}
@Transactional
public Order placeOrder(String sku, int quantity) {
if (!inventory.isInStock(sku, quantity)) {
throw new IllegalStateException("Not enough stock for " + sku);
}
var order = orders.save(new Order(sku, quantity, "PLACED"));
events.publishEvent(new OrderPlaced(order.getId(), order.getSku(), order.getQuantity()));
return order;
}
}</code></pre>
<p>Run the same test against this version:</p>
<pre><code class="language-console">org.springframework.modulith.core.Violations: - Cycle detected: Slice inventory ->
Slice order ->
Slice inventory
2. Dependencies of Slice order
- Field &lt;...OrderManagement.inventory> has type &lt;...inventory.InventoryManagement>
- Method &lt;...OrderManagement.placeOrder(String, int)> calls method
&lt;...inventory.InventoryManagement.isInStock(String, int)>
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 -- BUILD FAILURE
(No "non-exposed type" complaint this time -- InventoryManagement really is public.
Only "Cycle detected" remains.)</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/03-cycle-via-public-api-still-failed.txt">output/03-cycle-via-public-api-still-failed.txt</a></p>
<p>The non-exposed-type complaint is gone, exactly as expected &#8212;
<code>InventoryManagement</code> is a perfectly legitimate public type. The cycle is
still there, because the cycle was never about which types are public. It is about
direction, and the direction was already spoken for the moment
<code>inventory</code> chose to listen for <code>OrderPlaced</code>.</p>
<figure role="img" aria-label="Adding a dependency from order back to inventory, even through inventory's public API, closes a two-node cycle that ApplicationModules.verify() rejects.">
<svg viewBox="0 0 740 260" xmlns="http://www.w3.org/2000/svg">
<style>
.t{font:600 15px sans-serif;fill:#2b2f38}
.h{font:600 13px sans-serif;fill:#2b2f38}
.c{font:12px sans-serif;fill:#5b6270}
.lbl{font:11px sans-serif;fill:#5b6270}
.lbl2{font:11px sans-serif;fill:#c56a54}
</style>
<rect x="0" y="0" width="740" height="260" fill="#ffffff"/>
<text x="20" y="28" class="t">Closing the loop: order &#8596; inventory</text>
<rect x="140" y="80" width="150" height="56" rx="8" fill="#e8eefc" stroke="#5b7fc7"/>
<text x="215" y="113" class="h" text-anchor="middle">order</text>
<rect x="450" y="80" width="150" height="56" rx="8" fill="#e7f4ea" stroke="#4a9d63"/>
<text x="525" y="113" class="h" text-anchor="middle">inventory</text>
<!-- inventory -> order, existing, solid green -->
<path d="M 450 100 C 380 60, 310 60, 292 95" fill="none" stroke="#4a9d63" stroke-width="2" marker-end="url(#arrowg)"/>
<text x="330" y="55" class="lbl">listens to OrderPlaced (already there)</text>
<!-- order -> inventory, new, dashed red -->
<path d="M 292 125 C 360 165, 420 165, 448 128" fill="none" stroke="#c56a54" stroke-width="2.5" stroke-dasharray="5 4" marker-end="url(#arrowr)"/>
<text x="330" y="185" class="lbl2">calls InventoryManagement.isInStock(...) (the "fix")</text>
<defs>
<marker id="arrowg" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
<path d="M0,0 L8,4 L0,8 z" fill="#4a9d63"/>
</marker>
<marker id="arrowr" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
<path d="M0,0 L8,4 L0,8 z" fill="#c56a54"/>
</marker>
</defs>
<text x="20" y="225" class="c">Routing the second arrow through InventoryManagement &#8212; a real public type &#8212; removes the</text>
<text x="20" y="243" class="c">"non-exposed type" violation but not the cycle. verify() still fails: two arrows, two directions, one pair of modules.</text>
</svg>
</figure>
<p>The only fix that actually works is to not add the second edge. <code>order</code>
publishes <code>OrderPlaced</code> and stops caring what happens to it:</p>
<pre><code class="language-java">@Service
public class OrderManagement {
private final OrderRepository orders;
private final ApplicationEventPublisher events;
public OrderManagement(OrderRepository orders, ApplicationEventPublisher events) {
this.orders = orders;
this.events = events;
}
@Transactional
public Order placeOrder(String sku, int quantity) {
var order = orders.save(new Order(sku, quantity, "PLACED"));
events.publishEvent(new OrderPlaced(order.getId(), order.getSku(), order.getQuantity()));
return order;
}
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/main/java/com/ankurm/modulithdemo/order/OrderManagement.java">OrderManagement.java</a>
(final version)</p>
<pre><code class="language-console">Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in ModularityTests
BUILD SUCCESS
Same four modules, same ApplicationModules.verify() call, zero violations. The only
change from output/01 is that OrderManagement no longer depends on anything in
inventory, in either direction.</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/02-verify-passed.txt">output/02-verify-passed.txt</a></p>
<p>If inventory genuinely cannot satisfy an order, that has to travel back as a new
event <code>order</code> deliberately chooses to listen for &#8212; a second,
intentional relationship, not a shortcut around the first one. Keeping that
back-channel from becoming a cycle of its own is a big enough topic that it gets its
own post later in this series, on the Saga pattern.</p>
<div><details>
<summary><strong>Going deeper: NamedInterface and open modules &#8212; when a module needs to expose more than its base package</strong></summary>
<div style="padding:12px 4px 4px 4px">
<p>Sometimes a module genuinely needs to expose more than flat types in its base
package &#8212; an SPI sub-package meant for one or two trusted callers, say. Spring
Modulith has two escape hatches, both narrower than they look:</p>
<p><code>@NamedInterface("spi")</code> on a <code>package-info.java</code> inside
<code>inventory.spi</code> promotes that one sub-package to additional public API,
referenced from other modules&#8217; <code>@ApplicationModule(allowedDependencies =
"inventory :: spi")</code> declarations. It is scoped and explicit &#8212; exactly one
extra package, named in the dependency declaration of whoever is allowed to use it.</p>
<p><code>@ApplicationModule(type = Type.OPEN)</code> on the module&#8217;s
<code>package-info.java</code> is the blunt version: every internal type in that module
becomes visible to everyone. The reference documentation is direct about this not being
recommended for a well-modularized application, and after watching
<code>verify()</code> catch the <code>StockRepository</code> shortcut above, it should
be obvious why &#8212; <code>OPEN</code> does not fix the design problem, it just turns
off the thing that was telling you about it.</p>
<p>Neither of these would have saved the <code>order</code> &#8594; <code>inventory</code>
shortcut in this post. They widen who can see a module&#8217;s internals; they do
nothing about a cycle, which is a statement about direction, not visibility.</p>
</div>
</details></div>
<h2>How the cascade actually runs underneath</h2>
<p>Once <code>order</code> publishes <code>OrderPlaced</code> and gets out of the way,
three independent listeners pick it up. Here is <code>inventory</code>&#8217;s:</p>
<pre><code class="language-java">@Service
public class InventoryManagement {
private final StockRepository stock;
private final ApplicationEventPublisher events;
public boolean isInStock(String sku, int quantity) {
return stock.findBySku(sku).map(s -> s.getAvailable() >= quantity).orElse(false);
}
@ApplicationModuleListener
public void on(OrderPlaced event) {
var item = stock.findBySku(event.sku()).orElseThrow();
item.reserve(event.quantity());
stock.save(item);
events.publishEvent(new StockReserved(event.orderId(), event.sku(), item.getAvailable()));
}
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/main/java/com/ankurm/modulithdemo/inventory/InventoryManagement.java">InventoryManagement.java</a></p>
<p><code>@ApplicationModuleListener</code> looks like a plain marker annotation. It is
not. Reading the actual compiled class file &#8212; not the reference docs, the
bytecode &#8212; shows exactly what it expands to:</p>
<pre><code class="language-console">$ javap -v org/springframework/modulith/events/ApplicationModuleListener.class
RuntimeVisibleAnnotations:
0: Async
1: Transactional(propagation=Propagation.REQUIRES_NEW)
2: TransactionalEventListener</code></pre>
<p>So <code>@ApplicationModuleListener</code> is <code>@Async</code> +
<code>@Transactional(propagation = REQUIRES_NEW)</code> +
<code>@TransactionalEventListener</code>, stacked as meta-annotations on one
declaration. That combination is the whole mechanism:</p>
<ul>
<li><strong>@TransactionalEventListener</strong>, default phase <code>AFTER_COMMIT</code>:
the listener only runs once the transaction that published the event has actually
committed. Publish inside a transaction that rolls back, and the listener never fires
&#8212; which is correct, and also means publishing an event from code with no active
transaction at all silently does nothing. (<code>Scenario.publish()</code>, from the
test library, wraps the publish in its own transaction for exactly this reason.)</li>
<li><strong>@Async</strong>: the listener runs on a separate thread, after the
publishing method has already returned. <code>OrderManagement.placeOrder()</code>
finishes and gives the caller an <code>Order</code> back long before
<code>inventory</code> has reserved anything.</li>
<li><strong>@Transactional(REQUIRES_NEW)</strong>: the listener gets its own
transaction, independent of whatever was happening when the event was published. If the
listener fails, it cannot roll back the order that triggered it.</li>
</ul>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>Do not add your own @Transactional on top of this.</strong> It looks like harmless extra documentation of intent. It is not. A plain @Transactional (default propagation REQUIRED) stacked on an @ApplicationModuleListener method breaks Spring's own listener registration, and the whole ApplicationContext refuses to start:</blockquote>
<pre><code class="language-console">Caused by: java.lang.IllegalStateException: @TransactionalEventListener method must not
be annotated with @Transactional unless when declared as REQUIRES_NEW or NOT_SUPPORTED:
public void com.ankurm.modulithdemo.inventory.InventoryManagement.on(OrderPlaced)
at org.springframework.transaction.annotation
.RestrictedTransactionalEventListenerFactory.createApplicationListener(...)
Caused by: BeanInitializationException: Failed to process @EventListener annotation
on bean with name 'inventoryManagement'</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/05-redundant-transactional-failure.txt">output/05-redundant-transactional-failure.txt</a></p>
<p>This is a fail-fast mistake, at least &#8212; the context simply will not come up, so
it cannot ship silently. It is still worth knowing before it costs you a confused ten
minutes staring at a stack trace three frames removed from the line you actually
wrote.</p>
<p>Put the three listeners together and one <code>publishEvent()</code> call fans out
into four separate invocations, each on its own thread, in causal order but with no
ordering guarantee between independent branches:</p>
<figure role="img" aria-label="Timeline: placing an order publishes OrderPlaced, which inventory and notification react to independently; inventory's reservation then triggers shipping, which notification reacts to a second time.">
<svg viewBox="0 0 740 300" xmlns="http://www.w3.org/2000/svg">
<style>
.t{font:600 15px sans-serif;fill:#2b2f38}
.h{font:600 12px sans-serif;fill:#2b2f38}
.c{font:11px sans-serif;fill:#5b6270}
.m{font:11px monospace;fill:#2b2f38}
</style>
<rect x="0" y="0" width="740" height="300" fill="#ffffff"/>
<text x="20" y="26" class="t">One publishEvent() call, four listener invocations</text>
<!-- lanes -->
<text x="20" y="60" class="h">order</text>
<text x="20" y="120" class="h">inventory</text>
<text x="20" y="180" class="h">shipping</text>
<text x="20" y="240" class="h">notification</text>
<line x1="110" y1="60" x2="720" y2="60" stroke="#e2e5ea"/>
<line x1="110" y1="120" x2="720" y2="120" stroke="#e2e5ea"/>
<line x1="110" y1="180" x2="720" y2="180" stroke="#e2e5ea"/>
<line x1="110" y1="240" x2="720" y2="240" stroke="#e2e5ea"/>
<circle cx="150" cy="60" r="6" fill="#5b7fc7"/>
<text x="150" y="42" class="m" text-anchor="middle">placeOrder()</text>
<line x1="150" y1="60" x2="300" y2="120" stroke="#4a9d63" stroke-dasharray="2 3"/>
<circle cx="300" cy="120" r="6" fill="#4a9d63"/>
<text x="300" y="102" class="m" text-anchor="middle">on(OrderPlaced)</text>
<line x1="150" y1="60" x2="300" y2="240" stroke="#4a9d63" stroke-dasharray="2 3"/>
<circle cx="300" cy="240" r="6" fill="#4a9d63"/>
<text x="300" y="262" class="m" text-anchor="middle">on(OrderPlaced)</text>
<line x1="300" y1="120" x2="480" y2="180" stroke="#4a9d63" stroke-dasharray="2 3"/>
<circle cx="480" cy="180" r="6" fill="#4a9d63"/>
<text x="480" y="162" class="m" text-anchor="middle">on(StockReserved)</text>
<line x1="480" y1="180" x2="630" y2="240" stroke="#4a9d63" stroke-dasharray="2 3"/>
<circle cx="630" cy="240" r="6" fill="#4a9d63"/>
<text x="630" y="262" class="m" text-anchor="middle">on(ShipmentScheduled)</text>
<text x="20" y="290" class="c">Dashed lines are @ApplicationModuleListener hops &#8212; each runs async, in its own REQUIRES_NEW transaction, on its own thread.</text>
</svg>
</figure>
<p>Running the whole chain for real, from a test that boots all four modules together,
produces exactly that:</p>
<pre><code class="language-console">INFO [task-2] NotificationManagement : Order 1 received for 3x WIDGET-1
INFO [task-4] NotificationManagement : Order 1 is on its way (WIDGET-1)
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 -- BUILD SUCCESS</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/06-event-flow-passed.txt">output/06-event-flow-passed.txt</a></p>
<p>Getting that test to run at all &#8212; and the very specific way it fails the first
time &#8212; is its own lesson about a different Spring Modulith default, and it is
worth a section of its own.</p>
<h2>Testing an event cascade that crosses modules it does not depend on</h2>
<p><code>@ApplicationModuleTest</code> is Spring Modulith&#8217;s replacement for
<code>@SpringBootTest</code> in a single module&#8217;s tests: instead of booting the
entire application, it boots just the module under test, plus whichever other modules
<code>mode</code> tells it to include. <code>BootstrapMode.ALL_DEPENDENCIES</code>
sounds like exactly what you want for an integration test that follows an event across
three modules. Here is the first version of that test, written the way the name
suggests it should work:</p>
<p class="c">(annotation: <code>@ApplicationModuleTest(mode =
BootstrapMode.ALL_DEPENDENCIES)</code> on a test in the <code>order</code> package,
publishing <code>OrderPlaced</code> and waiting for <code>ShipmentScheduled</code>)</p>
<pre><code class="language-console">Bootstrapping @ApplicationModuleTest for Order in mode ALL_DEPENDENCIES
# Order
> Base package: com.ankurm.modulithdemo.order
> Direct module dependencies: none
> Spring beans:
+ ?.OrderController
+ ?.OrderManagement
o ?.internal.OrderRepository
org.awaitility.core.ConditionTimeoutException: ... expected the predicate to return
&lt;true> but it returned &lt;false> for input of &lt;[]> within 10 seconds.</code></pre>
<p class="c">Full transcript: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/04-event-flow-missing-dependency.txt">output/04-event-flow-missing-dependency.txt</a></p>
<p>Ten seconds of nothing, then a timeout. The log line that explains it is easy to
miss on a first read: <strong><code>Direct module dependencies: none</code></strong>.
<code>ALL_DEPENDENCIES</code> bootstraps the modules the module under test <em>depends
on</em> &#8212; the modules it imports from. It does not infer the reverse: modules that
depend on <em>it</em>, by listening for its events. <code>order</code> imports nothing
from <code>inventory</code>, <code>shipping</code>, or <code>notification</code> &#8212;
correctly, as the whole first half of this post just finished establishing &#8212; so
from <code>order</code>&#8217;s point of view, in this test, those three modules do not
exist. <code>InventoryManagement</code> is never instantiated. The event is published
into a context with no listener to receive it, and the test waits for something that
was never going to arrive.</p>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>ALL_DEPENDENCIES follows your code's import graph, not your event graph.</strong> If the thing you want to test is a reaction to an event &#8212; which, in an event-driven module boundary, is most of what there is to test &#8212; you have to say so explicitly.</blockquote>
<p>The fix is <code>extraIncludes</code>, which names modules to bootstrap regardless of
whether the module under test has a code dependency on them:</p>
<pre><code class="language-java">@ApplicationModuleTest(
mode = ApplicationModuleTest.BootstrapMode.ALL_DEPENDENCIES,
extraIncludes = { "inventory", "shipping", "notification" })
class OrderFulfillmentIntegrationTests {
@Test
void placingAnOrderCascadesThroughInventoryAndShipping(Scenario scenario) {
scenario.publish(new OrderPlaced(1L, "WIDGET-1", 3))
.andWaitForEventOfType(ShipmentScheduled.class)
.matching(event -> event.orderId().equals(1L))
.toArriveAndVerify(event -> {
if (!event.sku().equals("WIDGET-1")) {
throw new AssertionError("expected WIDGET-1, got " + event.sku());
}
});
}
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/test/java/com/ankurm/modulithdemo/order/OrderFulfillmentIntegrationTests.java">OrderFulfillmentIntegrationTests.java</a></p>
<p>With <code>inventory</code>, <code>shipping</code>, and <code>notification</code>
named explicitly, their listener beans exist, the cascade actually runs, and this is
the test that produced the passing transcript in the previous section. The
<code>Scenario</code> API itself &#8212; <code>publish(event).andWaitForEventOfType(X.class)
.matching(...).toArriveAndVerify(...)</code> &#8212; is Spring Modulith&#8217;s
Awaitility-backed way of asserting on an async, eventually-consistent chain without a
hand-rolled <code>Thread.sleep()</code>.</p>
<h2>What the defaults do not do</h2>
<p>Everything so far has been about getting the happy path to compile, pass, and run.
Two defaults are worth knowing about before this goes anywhere near production, because
neither one fails loudly.</p>
<p>Every <code>@ApplicationModuleListener</code> gets one row in the event publication
registry &#8212; a table Spring Modulith creates for you (via
<code>spring-modulith-starter-jpa</code> or <code>-jdbc</code>) the moment an event is
published, before the listener even runs:</p>
<figure role="img" aria-label="Event publication lifecycle: PUBLISHED moves to PROCESSING, then COMPLETED on success or FAILED on exception; FAILED can be resubmitted back to PROCESSING. A staleness monitor that would otherwise rescue a stuck row is disabled by default.">
<svg viewBox="0 0 740 260" xmlns="http://www.w3.org/2000/svg">
<style>
.t{font:600 15px sans-serif;fill:#2b2f38}
.h{font:600 12px sans-serif;fill:#2b2f38}
.c{font:11px sans-serif;fill:#5b6270}
</style>
<rect x="0" y="0" width="740" height="260" fill="#ffffff"/>
<text x="20" y="26" class="t">One row per @ApplicationModuleListener, per event</text>
<rect x="30" y="70" width="140" height="48" rx="8" fill="#fdeccf" stroke="#c9973f"/>
<text x="100" y="99" class="h" text-anchor="middle">PUBLISHED</text>
<rect x="230" y="70" width="140" height="48" rx="8" fill="#fdeccf" stroke="#c9973f"/>
<text x="300" y="99" class="h" text-anchor="middle">PROCESSING</text>
<rect x="430" y="20" width="140" height="48" rx="8" fill="#e7f4ea" stroke="#4a9d63"/>
<text x="500" y="49" class="h" text-anchor="middle">COMPLETED</text>
<rect x="430" y="120" width="140" height="48" rx="8" fill="#f7d9d3" stroke="#c56a54"/>
<text x="500" y="149" class="h" text-anchor="middle">FAILED</text>
<rect x="630" y="120" width="95" height="48" rx="8" fill="#fdeccf" stroke="#c9973f"/>
<text x="677" y="142" class="h" text-anchor="middle" font-size="11">RESUBMITTED</text>
<line x1="170" y1="94" x2="230" y2="94" stroke="#c9973f" stroke-width="2" marker-end="url(#a3)"/>
<line x1="370" y1="85" x2="430" y2="55" stroke="#4a9d63" stroke-width="2" marker-end="url(#a4)"/>
<text x="375" y="60" class="c">listener returns</text>
<line x1="370" y1="105" x2="430" y2="135" stroke="#c56a54" stroke-width="2" marker-end="url(#a5)"/>
<text x="375" y="135" class="c">listener throws</text>
<line x1="570" y1="144" x2="630" y2="144" stroke="#c9973f" stroke-width="2" marker-end="url(#a6)"/>
<path d="M 677 120 C 677 40, 600 20, 575 35" fill="none" stroke="#c9973f" stroke-width="2" stroke-dasharray="3 3" marker-end="url(#a7)"/>
<text x="585" y="15" class="c" font-size="10">on retry success</text>
<defs>
<marker id="a3" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#c9973f"/></marker>
<marker id="a4" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#4a9d63"/></marker>
<marker id="a5" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#c56a54"/></marker>
<marker id="a6" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#c9973f"/></marker>
<marker id="a7" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#c9973f"/></marker>
</defs>
<rect x="30" y="190" width="690" height="50" rx="6" fill="#f4f5f7" stroke="#b7bec9" stroke-dasharray="3 3"/>
<text x="45" y="210" class="c">A crash between PUBLISHED and PROCESSING leaves a row stuck. The staleness monitor that would</text>
<text x="45" y="228" class="c">mark it FAILED is off by default &#8212; all three spring.modulith.events.staleness.* durations default to zero.</text>
</svg>
</figure>
<p>That row is what makes the registry useful at all &#8212; it is how a listener that
threw an exception can be found and resubmitted later, and how a process that died
between "published" and "handled" does not just lose the event. But two defaults blunt
that guarantee more than the reference documentation&#8217;s tone suggests:</p>
<ul>
<li>The default completion mode is <code>UPDATE</code>: completed rows are marked
complete and left in the table, forever, growing without bound unless something purges
them. <code>DELETE</code> removes them (and loses the ability to query completed
publications); <code>ARCHIVE</code> moves them to a separate table first, which is
usually the one you actually want.</li>
<li>The staleness monitor &#8212; the background task that would notice a row stuck in
<code>PUBLISHED</code> or <code>PROCESSING</code> after a crash and mark it
<code>FAILED</code> so it becomes eligible for resubmission &#8212; is disabled by
default. All three <code>spring.modulith.events.staleness.*</code> durations default to
zero, which this library treats as "off", not "immediately stale".</li>
</ul>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>A crash at exactly the wrong moment leaves a row nobody is looking for, by default.</strong> Set the staleness durations and a non-UPDATE completion mode before this matters in production:</blockquote>
<pre><code class="language-yaml">spring.modulith.events.staleness.published=PT5M
spring.modulith.events.staleness.processing=PT5M
spring.modulith.events.staleness.resubmitted=PT5M
spring.modulith.events.completion-mode=ARCHIVE</code></pre>
<p>None of this is a defect in Spring Modulith &#8212; it is a reasonable default for a
library that has to work the same way whether you are prototyping on an in-memory H2
database or running a Kafka-backed outbox in production. It is, however, exactly the
kind of default that an architecture diagram does not show you, which is the theme of
this whole post applied one layer down: the tool that verifies your module boundaries
has its own quiet defaults, and they reward the same treatment &#8212; read the actual
behavior, not the one-paragraph summary.</p>
<h2>Generated documentation, not hand-maintained diagrams</h2>
<p>The module diagram earlier in this post, and the arrows in it, came from running
this:</p>
<pre><code class="language-java">@Test
void writesDocumentation() {
new Documenter(modules)
.writeModulesAsPlantUml()
.writeIndividualModulesAsPlantUml()
.writeModuleCanvases()
.writeAggregatingDocument();
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/test/java/com/ankurm/modulithdemo/ModularityTests.java">ModularityTests.java</a>
(the <code>writesDocumentation()</code> test)</p>
<p><code>Documenter</code> reads the same <code>ApplicationModules</code> model
<code>verify()</code> checks and writes a PlantUML component diagram, one PlantUML
diagram per module showing just that module&#8217;s direct dependencies, a tabular
"canvas" per module (Spring beans, grouped by stereotype), and an Asciidoc file linking
all of it together &#8212; to <code>target/spring-modulith-docs</code> by default.</p>
<div><details>
<summary><strong>The raw generated output for this app</strong></summary>
<div style="padding:12px 4px 4px 4px">
<pre><code class="language-console">Rel(Notification, Order, "listens to")
Rel(Shipping, Inventory, "listens to")
Rel(Inventory, Order, "listens to")
Rel(Notification, Shipping, "listens to")
module-order.adoc:
|Spring components
|_Controllers_
* c.a.m.o.OrderController
_Services_
* c.a.m.o.OrderManagement</code></pre>
<p>Full transcript, including every generated <code>.puml</code> and <code>.adoc</code>
file: <a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/output/07-generated-docs.txt">output/07-generated-docs.txt</a>. Note that the diagram the generator
produces is a C4-style PlantUML file meant for a build pipeline to render &#8212;
this post hand-draws the equivalent SVG instead, to match the rest of the
site, but the relationships in it are copied directly from this generated
output, not invented.</p>
</div>
</details></div>
<p>The practical value of this is less "pretty diagrams" and more "diagrams that cannot
quietly go stale", because they are regenerated from the actual compiled module
structure on every build, the same build that is already failing if that structure
violates its own rules.</p>
<h2>One more failure, worth a sentence, because it will happen to you too</h2>
<p>Before any of the module-boundary content above, the very first time this
repository&#8217;s tests ran against a real database, they failed on something that
has nothing to do with Spring Modulith at all:</p>
<pre><code class="language-console">org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement
"create table [*]order (id bigint ..., primary key (id))"; expected "identifier"</code></pre>
<p>Hibernate defaults a JPA entity&#8217;s table name to the class&#8217;s simple name.
<code>Order</code> the Java class becomes <code>order</code> the table, and
<code>ORDER</code> is a reserved SQL keyword &#8212; the <code>ORDER BY</code> clause
&#8212; in H2, Postgres, MySQL, and the SQL standard generally. The fix is one
annotation:</p>
<pre><code class="language-java">@Entity
@Table(name = "orders") // ORDER is a reserved SQL keyword (ORDER BY)
public class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sku;
private int quantity;
private String status;
}</code></pre>
<p class="c"><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/src/main/java/com/ankurm/modulithdemo/order/internal/Order.java">Order.java</a></p>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>If you are naming an entity after a core domain concept in an order-processing system, check it against your database's reserved-word list before the schema generator does it for you.</strong> ORDER, GROUP, USER, and DATE have all caught people this way at least once.</blockquote>
<h2>Should you reach for this?</h2>
<blockquote style="background:#f4f5f7;border:1px solid #e2e5ea;border-left:4px solid #b7bec9;border-radius:6px;padding:16px 20px;"><strong>Spring Modulith is worth adding the moment more than one person is working in the same Spring Boot codebase and "please don't reach into that package" has ever been said out loud in a code review.</strong> It is not worth adding to a single-developer side project, or to a monolith you are about to split into services anyway &#8212; in that case, write the ArchUnit rules for the specific boundary you are about to cut, run them for a few weeks, and extract. ApplicationModules.verify() earns its keep as a standing, automatically-discovered rule set across a whole codebase over months and years, not as a one-time check before a big refactor.</blockquote>
<p>The next post in this series uses this same repository to work through the question
that follows naturally from everything above: once your modules are genuinely decoupled
and verified, when &#8212; if ever &#8212; does it actually pay to split them into
separate services? And two posts after that, the Transactional Outbox post comes back
to the event publication registry diagram above and does something with the completion
states this one only described: externalizing events to Kafka, and replaying the ones
that got stuck.</p>
<h3>Further reading</h3>
<ul>
<li><a href="https://ankurm.com/git.app/asmhatre/spring-modulith-demo/src/branch/main/order-fulfillment/README.md">Companion repository README</a> &#8212; versions, module table, and an index of every captured transcript</li>
<li><a href="https://docs.spring.io/spring-modulith/reference/fundamentals.html" rel="nofollow">Spring Modulith reference &#8212; Fundamentals</a></li>
<li><a href="https://docs.spring.io/spring-modulith/reference/events.html" rel="nofollow">Spring Modulith reference &#8212; Application Events</a></li>
<li><a href="https://github.com/spring-projects/spring-modulith/releases/tag/2.1.1" rel="nofollow">Spring Modulith 2.1.1 release notes</a></li>
</ul>
<!-- /wp:html -->