Why this matters
- Tight coupling between
OrderServiceand email, analytics, and loyalty-point logic makes every change ripple through the codebase. - Events decouple the publisher from listeners — add a new reaction to
OrderPlacedwithout touching the checkout flow. - Transactional event listeners solve the classic problem of sending notifications before the database commit actually succeeds.
In-process events
L1 · FresherApplicationEventPublisher notifies listeners when something happens inside the same JVM — e.g. OrderPlacedEvent.
@EventListener
L2 · IntermediateMethods on Spring beans handle events synchronously by default; use @Async on the listener for fire-and-forget side effects.
Transactional events
L3 · Advanced@TransactionalEventListener(phase = AFTER_COMMIT) ensures listeners run only after the database commit succeeds.
Events vs messaging
L4 · ExpertEvents do not cross services — use Kafka or outbox when BookStore microservices must react to order placement.
Event API building blocks
ApplicationEventPublisher— inject this to publish events from any service.- Plain POJO events — any class can be an event; records work well for immutable payloads.
@EventListener— marks a method that reacts to a specific event type.@TransactionalEventListener— defers execution until a transaction commits, rolls back, or completes.@Asyncon listeners — runs the handler off the publishing thread; combine with transactional listeners carefully.
Define and publish an event
// learn:fragment
public record OrderPlacedEvent(
Long orderId,
String customerEmail,
BigDecimal totalAmount,
Instant placedAt
) {}
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 2 sections
- Listeners in separate beans
- Ordering and conditional listeners
Test yourself
Answer these before moving on — recall is what makes it stick.