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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
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.