Video in progress

Middle 🌱 Spring

How do events work in Spring with ApplicationEventPublisher and @EventListener?

One bean publishes an event, others listen for it with @EventListener. By default it's all synchronous — the listener runs on the publisher's thread and inside its transaction.

📖 Answer

public record UserRegistered(long userId, String email) {}

@Service
class RegistrationService {
    private final ApplicationEventPublisher events;

    @Transactional
    public void register(SignUp s) {
        User u = users.save(new User(s));
        events.publishEvent(new UserRegistered(u.getId(), u.getEmail()));
    }
}

@Component
class WelcomeMail {
    @EventListener
    void on(UserRegistered e) { mail.sendWelcome(e.email()); }
}

RegistrationService knows nothing about emails, bonuses or analytics — when you need a new reaction, you write a new listener, done.

Things to know:

  • if a listener throws, register fails too and the transaction rolls back;
  • the email goes out before the commit — if a rollback follows, a user who doesn't exist gets an email. That's what @TransactionalEventListener(phase = AFTER_COMMIT) is for;
  • if you need it asynchronous, add @Async to the listener.
  • Events stay inside a single application. They're not for messaging between services — that's Kafka/RabbitMQ.