You want to publish a custom event UserCreatedEvent and ensure multiple listeners react differently. Which approach correctly implements this in Spring Boot?
hard📝 Application Q15 of 15
Spring Boot - Advanced Patterns
You want to publish a custom event UserCreatedEvent and ensure multiple listeners react differently. Which approach correctly implements this in Spring Boot?
ACreate <code>UserCreatedEvent</code> extending ApplicationEvent, inject ApplicationEventPublisher, publish event, and annotate multiple methods with @EventListener for UserCreatedEvent
BCreate UserCreatedEvent as a simple POJO, call listeners manually without publishing events
CUse ApplicationEventPublisher to publish String messages instead of event objects
DCreate UserCreatedEvent but do not extend ApplicationEvent; rely on @EventListener to catch any object
Step-by-Step Solution
Solution:
Step 1: Define event class properly
Custom events should extend ApplicationEvent for Spring to recognize them.
Step 2: Publish event and create multiple listeners
Inject ApplicationEventPublisher to publish event. Use @EventListener on multiple methods to react differently.
Step 3: Evaluate other options
Create UserCreatedEvent as a simple POJO, call listeners manually without publishing events skips event system, losing decoupling. Use ApplicationEventPublisher to publish String messages instead of event objects misuses publisher with Strings. Create UserCreatedEvent but do not extend ApplicationEvent; rely on @EventListener to catch any object breaks event contract, listeners may not work.
Final Answer:
Create UserCreatedEvent extending ApplicationEvent, inject ApplicationEventPublisher, publish event, and annotate multiple methods with @EventListener for UserCreatedEvent -> Option A
Quick Check:
Proper event class + publisher + listeners = correct [OK]
Quick Trick:Extend ApplicationEvent and use @EventListener for multiple reactions [OK]
Common Mistakes:
Not extending ApplicationEvent for custom events
Calling listeners manually instead of publishing
Publishing wrong object types like String
Master "Advanced Patterns" in Spring Boot
9 interactive learning modes - each teaches the same concept differently