java
43 lines · 8 steps
Decoupling side effects with Spring events
A service publishes a domain event and a listener reacts only after the transaction commits, keeping order placement independent from notifications.
Explained by
highlit
1@Service
2public class OrderService {
3
4 private final OrderRepository orderRepository;
5 private final ApplicationEventPublisher eventPublisher;
6
7 public OrderService(OrderRepository orderRepository, ApplicationEventPublisher eventPublisher) {
8 this.orderRepository = orderRepository;
9 this.eventPublisher = eventPublisher;
10 }
11
12 @Transactional
13 public Order placeOrder(PlaceOrderCommand command) {
14 Order order = new Order(command.customerId(), command.items());
15 order.markPlaced();
16 orderRepository.save(order);
17
18 eventPublisher.publishEvent(new OrderPlacedEvent(order.getId(), order.getCustomerId(), order.getTotal()));
19 return order;
20 }
21}
22
23public record OrderPlacedEvent(Long orderId, Long customerId, BigDecimal total) {
24}
25
26@Component
27public class OrderPlacedListener {
28
29 private static final Logger log = LoggerFactory.getLogger(OrderPlacedListener.class);
30
31 private final NotificationService notificationService;
32
33 public OrderPlacedListener(NotificationService notificationService) {
34 this.notificationService = notificationService;
35 }
36
37 @Async
38 @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
39 public void onOrderPlaced(OrderPlacedEvent event) {
40 log.info("Order {} placed for customer {} totalling {}", event.orderId(), event.customerId(), event.total());
41 notificationService.sendOrderConfirmation(event.customerId(), event.orderId());
42 }
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Publishing a domain event lets the core operation stay ignorant of who reacts to it.
- 2AFTER_COMMIT listeners ensure side effects only fire once the data is durably saved.
- 3Combining @Async with transactional listeners moves slow work off the request thread without risking phantom notifications.
Related explainers
java
public final class Levenshtein { private Levenshtein() { }
Two-row Levenshtein distance in Java
dynamic-programming
edit-distance
space-optimization
Intermediate
8 steps
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
Intermediate
7 steps
java
package com.example.lb; import java.util.List; import java.util.concurrent.atomic.AtomicInteger;
A thread-safe round-robin load balancer in Java
concurrency
load-balancing
round-robin
Intermediate
9 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/decoupling-side-effects-with-spring-events-explained-java-4586/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.