Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 2: Persistence, Transactions & Security (11 - 24)

26%
Spring Boot & Microservices (50 Qs)•Part 2: Persistence, Transactions & Security (11 - 24)

What are Spring Events and how do you implement loose coupling?

junior LevelCode ExampleState ManagementSecurity & AuthDatabases & SQL

In Simple Words: Spring Events allow components to communicate asynchronously without direct dependencies:

  1. Publisher calls ApplicationEventPublisher.publishEvent(new OrderCreatedEvent(order)).
  2. Consumer listens via @EventListener or @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT).
  3. AFTER_COMMIT guarantees emails/Kafka events are only fired if the database transaction committed successfully.

Code Example

java
// 1. Immutable Domain Event
public record OrderCreatedEvent(Long orderId, String customerEmail, java.math.BigDecimal total) {}

// 2. Transaction-bound Listener (Executes ONLY after DB commit succeeds)
@Component
public class NotificationEventListener {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onOrderCreated(OrderCreatedEvent event) {
        emailService.sendOrderReceipt(event.customerEmail(), event.orderId());
    }
}

Code Example

java
// 1. Immutable Domain Event
public record OrderCreatedEvent(Long orderId, String customerEmail, java.math.BigDecimal total) {}

// 2. Transaction-bound Listener (Executes ONLY after DB commit succeeds)
@Component
public class NotificationEventListener {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onOrderCreated(OrderCreatedEvent event) {
        emailService.sendOrderReceipt(event.customerEmail(), event.orderId());
    }
}