📖 Scenario: You are building a simple Spring Boot application that needs to notify other parts of the app when a user registers. This notification will be done using Spring's event publishing system.
🎯 Goal: Create a Spring Boot application that publishes a custom event called UserRegisteredEvent using ApplicationEventPublisher. The event should carry the username of the registered user.
📋 What You'll Learn
Create a custom event class UserRegisteredEvent that extends ApplicationEvent and holds a username.
Create a Spring service class UserService that has a method registerUser(String username).
Inject ApplicationEventPublisher into UserService and publish UserRegisteredEvent inside registerUser.
Add a simple event listener component that listens for UserRegisteredEvent and prints the username.
💡 Why This Matters
🌍 Real World
Event publishing is useful in real applications to decouple components. For example, when a user registers, you might want to send a welcome email, update analytics, or log the event without tightly coupling these actions.
💼 Career
Understanding Spring's event system is important for building scalable and maintainable backend applications. Many enterprise applications use event-driven designs to improve modularity and responsiveness.
Progress0 / 4 steps
1
Create the custom event class
Create a class called UserRegisteredEvent that extends ApplicationEvent. Add a private final String username field, a constructor that takes Object source and String username, and a getter method getUsername().
Spring Boot
Hint
Remember to extend ApplicationEvent and call super(source) in the constructor.
2
Add ApplicationEventPublisher to UserService
Create a Spring service class called UserService. Inject ApplicationEventPublisher using constructor injection and store it in a private final field called eventPublisher.
Spring Boot
Hint
Use @Service annotation and constructor injection for ApplicationEventPublisher.
3
Publish UserRegisteredEvent in registerUser method
Inside UserService, add a public method registerUser(String username). Inside this method, create a new UserRegisteredEvent with this as source and the username. Then publish the event using eventPublisher.publishEvent().
Spring Boot
Hint
Create the event object and call publishEvent on eventPublisher.
4
Add event listener to handle UserRegisteredEvent
Create a Spring component class called UserRegisteredListener. Add a method handleUserRegisteredEvent(UserRegisteredEvent event) annotated with @EventListener. Inside the method, print the username using System.out.println("User registered: " + event.getUsername()).
Spring Boot
Hint
Use @Component and @EventListener annotations to create the listener.
Practice
(1/5)
1. What is the primary role of ApplicationEventPublisher in a Spring Boot application?
easy
A. To manage HTTP requests and responses
B. To listen and handle events automatically
C. To configure database connections
D. To send or publish events within the application
Solution
Step 1: Understand the purpose of ApplicationEventPublisher
This interface is designed to publish events to listeners within the Spring application context.
Step 2: Differentiate from listeners and other components
Listeners handle events, but ApplicationEventPublisher only sends or publishes them.
Final Answer:
To send or publish events within the application -> Option D
Quick Check:
Event sending = ApplicationEventPublisher [OK]
Hint: Publisher sends events; listeners receive them [OK]
Common Mistakes:
Confusing publisher with listener
Thinking it manages HTTP or database
Assuming it handles event processing
2. Which of the following is the correct way to inject ApplicationEventPublisher in a Spring Boot component?
easy
A. @Autowired private ApplicationEventPublisher publisher;
B. private ApplicationEventPublisher publisher = new ApplicationEventPublisher();
C. @Inject ApplicationEventPublisher publisher = null;
D. ApplicationEventPublisher publisher = ApplicationEventPublisher.getInstance();
Solution
Step 1: Recall Spring dependency injection syntax
Spring uses @Autowired to inject beans automatically into components.
Step 2: Check each option for correctness
@Autowired private ApplicationEventPublisher publisher; uses @Autowired correctly. private ApplicationEventPublisher publisher = new ApplicationEventPublisher(); tries to instantiate interface (not allowed). @Inject ApplicationEventPublisher publisher = null; mixes @Inject with assignment (not typical in Spring). ApplicationEventPublisher publisher = ApplicationEventPublisher.getInstance(); uses a non-existent getInstance method.
Final Answer:
@Autowired private ApplicationEventPublisher publisher; -> Option A
Quick Check:
@Autowired injects beans properly [OK]
Hint: Use @Autowired for Spring bean injection [OK]
Common Mistakes:
Trying to instantiate ApplicationEventPublisher directly
Mixing injection annotations incorrectly
Using static getInstance() which doesn't exist
3. Given the following code snippet, what will be printed when publishEvent() is called?
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) { super(source); }
}
@Component
public class MyPublisher {
@Autowired
private ApplicationEventPublisher publisher;
public void publishEvent() {
publisher.publishEvent(new MyEvent(this));
}
}
@Component
public class MyListener {
@EventListener
public void handleMyEvent(MyEvent event) {
System.out.println("Event received");
}
}
medium
A. No output
B. Compilation error
C. Event received
D. Runtime exception
Solution
Step 1: Understand event publishing and listening
The publisher sends a MyEvent instance. The listener listens for MyEvent and prints "Event received".
Step 2: Confirm no errors in code
Code uses correct annotations and event class extending ApplicationEvent, so no errors or exceptions.
Final Answer:
Event received -> Option C
Quick Check:
Listener prints message on event [OK]
Hint: Listener prints message when event is published [OK]
Common Mistakes:
Forgetting @EventListener annotation
Not extending ApplicationEvent in event class
Expecting output without publishing event
4. Identify the error in the following Spring Boot event publishing code:
@Component
public class EventSender {
private ApplicationEventPublisher publisher;
public void send() {
publisher.publishEvent(new CustomEvent(this));
}
}
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) { super(source); }
}
medium
A. send method should be static
B. ApplicationEventPublisher is not injected, so publisher is null
C. publishEvent method does not exist
D. CustomEvent does not extend ApplicationEvent
Solution
Step 1: Check ApplicationEventPublisher usage
The publisher field is declared but never injected or assigned, so it remains null.
Step 2: Consequence of null publisher
Calling publishEvent on null causes NullPointerException at runtime.
Final Answer:
ApplicationEventPublisher is not injected, so publisher is null -> Option B
Quick Check:
Missing injection causes null publisher [OK]
Hint: Always inject ApplicationEventPublisher before use [OK]
Common Mistakes:
Forgetting @Autowired on publisher
Assuming interface can be instantiated
Thinking method must be static
5. You want to publish a custom event UserCreatedEvent and ensure multiple listeners react differently. Which approach correctly implements this in Spring Boot?
hard
A. Create UserCreatedEvent extending ApplicationEvent, inject ApplicationEventPublisher, publish event, and annotate multiple methods with @EventListener for UserCreatedEvent
B. Create UserCreatedEvent as a simple POJO, call listeners manually without publishing events
C. Use ApplicationEventPublisher to publish String messages instead of event objects
D. Create UserCreatedEvent but do not extend ApplicationEvent; rely on @EventListener to catch any object
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]
Hint: 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.