Spring's application event system lets different parts of an application communicate about significant activities in a decoupled way, using publisher and listener components connected through the Spring container rather than direct method calls.
Key Points: • Define a custom event class, typically extending ApplicationEvent or as a plain POJO, representing the activity, such as UserRegisteredEvent. • Publish events anywhere in the application using ApplicationEventPublisher.publishEvent(), without knowing who's listening. • Write listener methods annotated with @EventListener that react to a specific event type when it's published. • Listeners can run asynchronously by adding @Async alongside @EventListener, so publishing doesn't block on listener execution. • This pattern keeps modules loosely coupled, since the publisher never directly references the listener classes.
Example: When a new user signs up, the UserService publishes a UserRegisteredEvent; separate listeners react independently, one sends a welcome email and another provisions a default workspace, without the UserService knowing either of those listeners exist.
Code Example:
public class UserRegisteredEvent {
private final String email;
public UserRegisteredEvent(String email) { this.email = email; }
public String getEmail() { return email; }
}
@Component
public class WelcomeEmailListener {
@EventListener
public void onUserRegistered(UserRegisteredEvent event) {
emailService.sendWelcome(event.getEmail());
}
}Interview Tip: A concise interview answer is:
"I'd model significant activities as custom event classes, publish them with ApplicationEventPublisher wherever they occur, and write separate @EventListener methods that react independently. That decouples the code that triggers an activity from the code that reacts to it, so I can add new listeners later without touching the publisher."