Bird
0
0

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:
  1. Step 1: Define event class properly

    Custom events should extend ApplicationEvent for Spring to recognize them.
  2. Step 2: Publish event and create multiple listeners

    Inject ApplicationEventPublisher to publish event. Use @EventListener on multiple methods to react differently.
  3. 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.
  4. Final Answer:

    Create UserCreatedEvent extending ApplicationEvent, inject ApplicationEventPublisher, publish event, and annotate multiple methods with @EventListener for UserCreatedEvent -> Option A
  5. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes