Bird
0
0

Examine the following Spring component:

medium📝 Debug Q6 of 15
Spring Boot - Advanced Patterns
Examine the following Spring component:
@Component
public class EventSender {
    private ApplicationEventPublisher publisher;

    public void sendEvent() {
        publisher.publishEvent(new CustomEvent(this));
    }
}

What is the main issue with this code?
AThe <code>publishEvent</code> method does not exist in <code>ApplicationEventPublisher</code>
BThe <code>ApplicationEventPublisher</code> is not injected, so <code>publisher</code> is null
CThe <code>CustomEvent</code> class must extend <code>ApplicationListener</code> instead of <code>ApplicationEvent</code>
DThe <code>sendEvent</code> method must be annotated with <code>@EventListener</code>
Step-by-Step Solution
Solution:
  1. Step 1: Check field injection

    The publisher field is declared but not injected via @Autowired or constructor.
  2. Step 2: Consequence

    Without injection, publisher remains null, causing a NullPointerException when publishEvent is called.
  3. Step 3: Verify other options

    The publishEvent method does not exist in ApplicationEventPublisher is false; publishEvent exists. The CustomEvent class must extend ApplicationListener instead of ApplicationEvent is incorrect; events extend ApplicationEvent. The sendEvent method must be annotated with @EventListener is wrong; @EventListener is for listener methods, not publishers.
  4. Final Answer:

    The ApplicationEventPublisher is not injected, so publisher is null -> Option B
  5. Quick Check:

    Always inject ApplicationEventPublisher before use [OK]
Quick Trick: Missing @Autowired causes null ApplicationEventPublisher [OK]
Common Mistakes:
  • Forgetting to inject ApplicationEventPublisher
  • Confusing event and listener classes
  • Misusing @EventListener annotation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes