0 day streak
java / expert
Snippet

Eventual Consistency with TransactionalEventListener

To ensure external side effects (like sending emails) only occur if a transaction successfully commits, use @TransactionalEventListener with the AFTER_COMMIT phase.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
public class UserProcessor {
private final ApplicationEventPublisher publisher;
@Transactional
public void registerUser(User user) {
repository.save(user);
publisher.publishEvent(new UserRegisteredEvent(user));
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleUserRegistration(UserRegisteredEvent event) {
emailService.sendWelcomeEmail(event.getUser());
}
}
spring
Breakdown
1
phase = TransactionPhase.AFTER_COMMIT
Specifies that the listener should only run after the transaction has been committed.
2
publisher.publishEvent(...)
Dispatches the event within the current transactional context.