เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง
แยกโมดูลออกจากกันด้วยเหตุการณ์โดเมนที่เผยแพร่และใช้งานภายในบริบทแอปพลิเคชัน
เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Decouple Modules with Events?
In a modular monolith, an Order module often needs to trigger work in other modules: send a confirmation email, update inventory, award loyalty points. The naive approach is to have OrderService call EmailService, InventoryService, and LoyaltyService directly.
- This creates tight coupling — Order depends on every downstream module.
- Adding a new reaction means editing
OrderServiceagain. - Modules can no longer evolve or be tested independently.
Spring's internal application events invert this: the Order module simply publishes a domain event, and interested modules listen for it. The publisher never knows who is listening.
The Domain Event Record
An internal event is just a plain object — in Spring Boot 4 (Java 21+) a record is the idiomatic choice. It should be immutable and carry only the data listeners need.
- Name it in the past tense (
OrderCompleted) — it describes something that already happened. - Keep it inside the owning module's package.
- No Spring annotations are required on the event itself.
package com.shop.order;
import java.math.BigDecimal;
import java.util.UUID;
public record OrderCompleted(
UUID orderId,
String customerEmail,
BigDecimal total) {
}Publishing an Event
The owning module publishes the event through Spring's ApplicationEventPublisher. Inject it via the constructor and call publishEvent() after the business operation succeeds.
- The publisher has no compile-time reference to any listener.
- By default publishing is synchronous — listeners run on the same thread, inside the same transaction.
package com.shop.order;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class OrderService {
private final ApplicationEventPublisher events;
private final OrderRepository orders;
public OrderService(ApplicationEventPublisher events, OrderRepository orders) {
this.events = events;
this.orders = orders;
}
@Transactional
public void complete(Order order) {
order.markCompleted();
orders.save(order);
events.publishEvent(
new OrderCompleted(order.getId(), order.getCustomerEmail(), order.getTotal()));
}
}Listening with @EventListener
Any Spring bean in another module can react by annotating a method with @EventListener. The single method parameter declares the event type the listener cares about.
- The method can have any name — Spring matches on the parameter type.
- The listener lives in its own module (
com.shop.notification) and never references the Order service.
package com.shop.notification;
import com.shop.order.OrderCompleted;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class OrderEmailListener {
private final MailSender mail;
public OrderEmailListener(MailSender mail) {
this.mail = mail;
}
@EventListener
void on(OrderCompleted event) {
mail.send(event.customerEmail(),
"Your order " + event.orderId() + " is complete!");
}
}Synchronous by Default — and Its Risks
By default publishEvent() invokes every matching @EventListener synchronously, in order, on the calling thread. Because the listeners run inside the publisher's transaction:
- A listener that throws will propagate the exception back to the publisher and roll back the whole transaction.
- A slow listener (e.g. sending an email) blocks the business call until it finishes.
This is rarely what you want for side effects like email. The next scenes show how to fix both problems with transaction-bound and asynchronous listeners.
Reacting Only After Commit
You usually want side effects to fire only if the transaction actually commits — you should not send a "your order is complete" email if the order save later rolls back. Use @TransactionalEventListener, which by default binds to the AFTER_COMMIT phase.
- The listener runs after the publisher's transaction commits successfully.
- If the transaction rolls back, the listener is skipped.
- You can choose other phases via
phase = BEFORE_COMMIT,AFTER_ROLLBACK, orAFTER_COMPLETION.
package com.shop.notification;
import com.shop.order.OrderCompleted;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
@Component
public class OrderEmailListener {
private final MailSender mail;
public OrderEmailListener(MailSender mail) {
this.mail = mail;
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void on(OrderCompleted event) {
mail.send(event.customerEmail(),
"Your order " + event.orderId() + " is complete!");
}
}Making Listeners Asynchronous
To stop a slow listener from blocking the caller, add @Async. The listener then runs on a separate thread from a task executor, so publishEvent() returns immediately.
- Enable async support once with
@EnableAsyncon a configuration class. - Important: an
@Asynclistener runs in its own thread with no transaction and no access to the publisher's context. Combine it with@TransactionalEventListener(AFTER_COMMIT)when you want "after commit, on a background thread." - Async listeners that throw are logged but do not affect the publisher — handle failures yourself.
package com.shop.notification;
import com.shop.order.OrderCompleted;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
@Component
public class OrderEmailListener {
private final MailSender mail;
public OrderEmailListener(MailSender mail) {
this.mail = mail;
}
@Async
@TransactionalEventListener
void on(OrderCompleted event) {
mail.send(event.customerEmail(),
"Your order " + event.orderId() + " is complete!");
}
}Spring Modulith Event Externalization
Plain Spring events are in-memory only: if the application crashes between commit and the listener running, the event is lost. Spring Modulith adds durability with its Event Publication Registry.
- Add the
spring-modulith-events-jpa(or JDBC/MongoDB) starter. - Each
@TransactionalEventListenerinvocation is recorded in anevent_publicationtable within the same transaction. - Once the listener completes, its publication is marked as completed. Incomplete publications can be republished on restart, guaranteeing at-least-once delivery.
Configuring the Publication Registry
With the events starter on the classpath, Modulith auto-creates the registry schema and wires interception. A little YAML controls recovery behaviour.
republish-outstanding-events-on-restartresubmits any publications that never completed before the last shutdown.- Modulith also exposes the registry so you can monitor or manually resubmit stuck events.
spring:
modulith:
events:
jdbc:
schema-initialization:
enabled: true
republish-outstanding-events-on-restart: true
completion-mode: deleteFiltering Events by Condition
Sometimes a listener should only react to some events of a type. The condition attribute takes a SpEL expression evaluated against the event; the listener runs only when it returns true.
- Reference the event payload with
#root.eventor simply the property via#root. - This keeps filtering declarative instead of an
ifat the top of the method.
package com.shop.loyalty;
import com.shop.order.OrderCompleted;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class HighValueOrderListener {
// Only fires for orders over 100
@EventListener(condition = "#event.total().compareTo(new java.math.BigDecimal('100')) > 0")
void onBigOrder(OrderCompleted event) {
// award bonus loyalty points
}
}A Standalone Pub/Sub Mental Model
Strip away Spring and the pattern is just a registry of listeners keyed by event type. The snippet below is a plain Java program that mimics the synchronous publish/subscribe behaviour — useful to internalize what ApplicationEventPublisher does under the hood.
import java.util.*;
import java.util.function.Consumer;
public class MiniEventBus {
private final Map<Class<?>, List<Consumer<Object>>> listeners = new HashMap<>();
<T> void subscribe(Class<T> type, Consumer<T> listener) {
listeners.computeIfAbsent(type, k -> new ArrayList<>())
.add(e -> listener.accept(type.cast(e)));
}
void publish(Object event) {
listeners.getOrDefault(event.getClass(), List.of())
.forEach(l -> l.accept(event));
}
record OrderCompleted(String id, double total) {}
public static void main(String[] args) {
MiniEventBus bus = new MiniEventBus();
bus.subscribe(OrderCompleted.class,
e -> System.out.println("Email: order " + e.id() + " done"));
bus.subscribe(OrderCompleted.class,
e -> System.out.println("Loyalty: +" + (int) e.total() + " points"));
bus.publish(new OrderCompleted("A-42", 150.0));
}
}Quick Check: Choosing the Right Listener
You publish an OrderCompleted event inside a @Transactional order-save method. The email listener must run only if the order is actually persisted, and it must not delay or break the order-save call. Which listener configuration is correct?
Recap: Internal Events for Module Decoupling
You learned how to decouple modules with in-application domain events:
- Model events as immutable past-tense records owned by the publishing module.
- Publish via
ApplicationEventPublisher.publishEvent()— the publisher never references listeners. - React with
@EventListener(synchronous, in-transaction) or@TransactionalEventListener(runs in a chosen transaction phase, default AFTER_COMMIT). - Add
@Async+@EnableAsyncto run side effects off the caller's thread. - Filter declaratively with the
conditionSpEL attribute. - Use Spring Modulith's Event Publication Registry to persist publications and republish incomplete ones on restart for reliable, at-least-once delivery.
The result: modules that communicate through events stay independently testable, replaceable, and free of direct dependencies.
คำถามที่พบบ่อย
บทเรียน “เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง”
แยกโมดูลออกจากกันด้วยเหตุการณ์โดเมนที่เผยแพร่และใช้งานภายในบริบทแอปพลิเคชัน คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- โมดูลแอปพลิเคชันและการตรวจสอบขอบเขต
- เหตุการณ์ภายในแอปพลิเคชันและตัวรับฟัง
- การเผยแพร่เหตุการณ์เชิงธุรกรรมและเอาต์บ็อกซ์
- การทดสอบการผสานรวมโมดูลและสถานการณ์