Interview question
How does @EventListener work in Spring Boot? Compare with pub-sub and messaging. @EventListener Spring Boot में कैसे काम करता है? Pub-sub और messaging से compare करें।
Answer
@EventListener is Spring's built-in in-process event handling mechanism using ApplicationEventPublisher. Lightweight for local communication but synchronous by default. Use with @Async for async handling, or choose Kafka/RabbitMQ for distributed systems.
// Local In-Process Events
// Event definition
public class UserRegisteredEvent extends ApplicationEvent {
private String email;
public UserRegisteredEvent(Object source, String email) {
super(source);
this.email = email;
}
public String getEmail() {
return email;
}
}
// Event publisher
@Service
public class UserService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void registerUser(String email) {
// Register user logic
eventPublisher.publishEvent(new UserRegisteredEvent(this, email));
}
}
// Event listeners
@Component
public class EmailNotificationListener {
@EventListener
public void onUserRegistered(UserRegisteredEvent event) {
System.out.println('Sending email to: ' + event.getEmail());
// Send email
}
}
@Component
public class AnalyticsListener {
@EventListener
public void onUserRegistered(UserRegisteredEvent event) {
System.out.println('Logging user signup');
// Log to analytics
}
}
// Async event handling
@Component
public class SlowTaskListener {
@EventListener
@Async
public void onUserRegistered(UserRegisteredEvent event) {
// Runs in separate thread
System.out.println('Processing long task for: ' + event.getEmail());
// Heavy operation
}
}
// Conditional listeners
@Component
public class ConditionalListener {
@EventListener(condition = "#event.email.endsWith('@company.com')")
public void onInternalUserRegistered(UserRegisteredEvent event) {
System.out.println('Internal user registered');
}
}
// Comparison:
// @EventListener: In-process, synchronous, JVM-local
// Kafka/RabbitMQ: Distributed, async, network-based
// Use @EventListener for:
// 1. Simple internal communication
// 2. Loosely coupled components
// 3. When all services in same JVM
// 4. Local event broadcasting
// Use Kafka/RabbitMQ for:
// 1. Microservices communication
// 2. Event sourcing
// 3. Cross-service notifications
// 4. Message persistence needed@EventListener:
Local events भेजने के लिए
ApplicationEventPublisher.publishEvent()
Synchronous by default:
@EventListener
public void handle(Event event) { }
Asynchronous:
@EventListener
@Async
public void handle(Event event) { }
Conditional:
@EventListener(condition = "expression")
public void handle(Event event) { }
Comparison:
@EventListener - In-process
Kafka/RabbitMQ - Distributed
When use करें:
- Local: @EventListener
- Microservices: Kafka/RabbitMQ
- Persistence: Kafka/RabbitMQWas this answer clear?