Event-driven architecture pattern with Spring Boot
📖 Scenario: You are building a simple Spring Boot application that uses event-driven architecture to notify when a new user registers.This pattern helps different parts of your app communicate by sending and listening to events, like sending a welcome message when a user signs up.
🎯 Goal: Create a Spring Boot app that defines a user registration event, publishes it when a user registers, and listens to that event to print a welcome message.
📋 What You'll Learn
Create a UserRegisteredEvent class extending ApplicationEvent
Create a UserService class that publishes UserRegisteredEvent
Create a UserRegisteredListener class that listens for UserRegisteredEvent
Trigger the event when a user registers
💡 Why This Matters
🌍 Real World
Event-driven architecture is used in modern applications to decouple components and improve scalability by reacting to events like user actions or system changes.
💼 Career
Understanding event-driven patterns is important for backend developers working with Spring Boot to build responsive and maintainable applications.
Progress0 / 4 steps
1
Create the UserRegisteredEvent class
Create a class called UserRegisteredEvent that extends ApplicationEvent. Add a private 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
Create the UserService to publish events
Create a class called UserService annotated with @Service. Inject ApplicationEventPublisher with a private final field and constructor. Add a method registerUser(String username) that publishes a new UserRegisteredEvent with this as source and the username.
Spring Boot
Hint
Use constructor injection for ApplicationEventPublisher and call publishEvent inside registerUser.
3
Create the UserRegisteredListener to handle events
Create a class called UserRegisteredListener annotated with @Component. Add a method handleUserRegistered annotated with @EventListener that takes a UserRegisteredEvent parameter. Inside the method, print a welcome message using event.getUsername().
Spring Boot
Hint
Use @EventListener on the method that takes UserRegisteredEvent and prints the welcome message.
4
Trigger the event in the main application
In the main Spring Boot application class, inject UserService with @Autowired. In the run method of CommandLineRunner, call registerUser("Alice") on the injected UserService to trigger the event.
Spring Boot
Hint
Use CommandLineRunner to run code after the app starts and call registerUser with "Alice".
Practice
(1/5)
1. What is the main purpose of the event-driven architecture pattern in Spring Boot?
easy
A. To store data in a relational database
B. To allow different parts of the application to communicate by sending and receiving events
C. To create user interfaces with HTML and CSS
D. To handle HTTP requests directly without any middleware
This pattern lets components send and listen to events to communicate asynchronously.
Step 2: Identify Spring Boot usage
Spring Boot uses Java classes and annotations to implement this pattern for flexible communication.
Final Answer:
To allow different parts of the application to communicate by sending and receiving events -> Option B
Quick Check:
Event-driven communication = To allow different parts of the application to communicate by sending and receiving events [OK]
Hint: Event-driven means parts talk by sending/listening events [OK]
Common Mistakes:
Confusing event-driven with database storage
Thinking it handles UI design
Assuming it processes HTTP requests directly
2. Which annotation is used in Spring Boot to mark a method as an event listener?
easy
A. @EventHandler
B. @Listener
C. @HandleEvent
D. @EventListener
Solution
Step 1: Recall Spring Boot event listener annotation
Spring Boot uses @EventListener to mark methods that listen for events.
Step 2: Check other options
@EventHandler, @Listener, and @HandleEvent are not valid Spring Boot annotations for event listening.
Final Answer:
@EventListener -> Option D
Quick Check:
@EventListener marks event methods [OK]
Hint: Remember: @EventListener listens to events in Spring Boot [OK]
Common Mistakes:
Using @EventHandler which is not a Spring Boot annotation
Confusing with @Listener or @HandleEvent which don't exist
Misspelling the annotation name
3. Given this Spring Boot event publishing code snippet, what will be printed?
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) { super(source); }
}
@Component
public class Publisher {
@Autowired
private ApplicationEventPublisher publisher;
public void publish() {
publisher.publishEvent(new MyEvent(this));
}
}
@Component
public class Listener {
@EventListener
public void onMyEvent(MyEvent event) {
System.out.println("Event received");
}
}
medium
A. Event received
B. No output
C. Compilation error
D. Runtime exception
Solution
Step 1: Understand event publishing
The Publisher publishes a MyEvent instance using ApplicationEventPublisher.
Step 2: Understand event listening
The Listener class has a method annotated with @EventListener that listens for MyEvent and prints "Event received".
Final Answer:
Event received -> Option A
Quick Check:
Publishing triggers listener print = Event received [OK]
4. What is wrong with this Spring Boot event listener code?
@Component
public class MyListener {
@EventListener
public void handleEvent(String event) {
System.out.println("Event: " + event);
}
}
medium
A. EventListener methods cannot accept String as event parameter
B. Missing @Component annotation
C. Method must return a value
D. EventListener annotation is misspelled
Solution
Step 1: Check event parameter type
Spring events can be any object, including String, but using String as event parameter is discouraged because it may cause ambiguity and unintended triggers.
Step 2: Understand best practice
Using custom event classes extending ApplicationEvent or plain objects is preferred for clarity and to avoid conflicts.
Final Answer:
EventListener methods cannot accept String as event parameter -> Option A
Quick Check:
String event param is invalid for event listener [OK]
Hint: EventListener needs custom event class, not String [OK]
Common Mistakes:
Thinking @Component is missing
Believing method must return a value
Assuming annotation is misspelled
5. You want to build a Spring Boot app where multiple components react to a user registration event asynchronously. Which approach best fits the event-driven architecture pattern?
hard
A. Send HTTP requests manually between components
B. Call all components directly from the registration method without events
C. Create a UserRegisteredEvent class, publish it with ApplicationEventPublisher, and have multiple @EventListener methods handle it
D. Use a database trigger to notify components
Solution
Step 1: Identify event-driven pattern usage
Creating a custom event class and publishing it allows decoupled communication between components.
Step 2: Understand asynchronous handling
Multiple @EventListener methods can react independently and asynchronously to the event.
Step 3: Evaluate other options
Direct calls, database triggers, or manual HTTP requests do not follow Spring Boot event-driven best practices.
Final Answer:
Create a UserRegisteredEvent class, publish it with ApplicationEventPublisher, and have multiple @EventListener methods handle it -> Option C
Quick Check:
Custom event + publisher + listeners = Create a UserRegisteredEvent class, publish it with ApplicationEventPublisher, and have multiple @EventListener methods handle it [OK]
Hint: Use custom event class and @EventListener for async reactions [OK]
Common Mistakes:
Calling components directly, losing decoupling
Relying on database triggers for app events
Manually sending HTTP requests between components
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.