🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Spring’s event-driven architecture allows beans to communicate without tightly coupling to each other. This makes your code cleaner, modular, and easier to maintain.
In this guide, you’ll learn how to create, publish, and listen to custom events in Spring — with real-world use cases like sending welcome emails, logging actions, or triggering workflows.
✅ What Is a Spring Event?
A Spring event is a message object that one bean publishes and another listens for. It uses the Observer pattern, allowing decoupled communication between components.
Spring already includes built-in events like ContextRefreshedEvent, but you can define your own custom events for your application logic.
🧱 Step-by-Step: Creating a Custom Event
✨ Step 1: Define the Event Class
Extend ApplicationEvent (or use a POJO in Spring 4.2+).
public class UserRegisteredEvent extends ApplicationEvent {
private final String email;
public UserRegisteredEvent(Object source, String email) {
super(source);
this.email = email;
}
public String getEmail() {
return email;
}
}
✅ From Spring 4.2 onward, you can also use any POJO — no need to extend ApplicationEvent.
🚀 Step 2: Publish the Event
Inject ApplicationEventPublisher and fire the event when needed.
@Service
public class UserService {
private final ApplicationEventPublisher publisher;
public UserService(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void registerUser(String email) {
// Save user to DB (mocked here)
System.out.println("User registered: " + email);
// Publish custom event
publisher.publishEvent(new UserRegisteredEvent(this, email));
}
}
👂 Step 3: Listen to the Event
Use @EventListener on a method to handle the event.
@Component
public class WelcomeEmailListener {
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println("Sending welcome email to: " + event.getEmail());
}
}
🧪 Real-World Example: User Registration Flow
Let's simulate a complete flow:
- UserService registers the user
- Fires
UserRegisteredEvent - WelcomeEmailListener sends a welcome email
- AuditLogger logs the event
@Component
public class AuditLogger {
@EventListener
public void logEvent(UserRegisteredEvent event) {
System.out.println("Audit: New user registered - " + event.getEmail());
}
}
🔄 Bonus: Make Listeners Asynchronous
To make your listener non-blocking, annotate it with @Async.
@Async
@EventListener
public void sendWelcomeEmail(UserRegisteredEvent event) {
// send email in background
}
Enable async support in your config:
@SpringBootApplication
@EnableAsync
public class Application { }
✅ This improves performance and responsiveness for non-critical tasks like sending emails or analytics tracking.
💡 When to Use Custom Events
- 📨 Email notifications: Send welcome or reset password emails after user actions
- 📊 Audit logging: Record changes in a separate service
- 🧪 Testing hooks: Trigger test data setup or cleanup
- 📦 Workflow triggers: Start downstream services or microservices after state changes
⚠️ When Not to Use Events
- Avoid using events when you need guaranteed execution or immediate result.
- Don’t use it for core business logic that must succeed — prefer service method calls instead.
- Events are better for side effects, not primary outcomes.
✅ Best Practices
- Keep event classes immutable (use
finalfields). - Use POJOs for simplicity unless you need features of
ApplicationEvent. - Don’t assume listener execution order unless using
@Order. - Prefer
@EventListenerover implementingApplicationListener.
📌 Summary
| Component | Purpose |
|---|---|
| Event Class | Defines the custom data being passed |
| Publisher | Sends the event using publishEvent() |
| Listener | Listens for and reacts to the event |
| Async Events | Improves performance for background tasks |
🔚 Final Thoughts
Spring’s event system is powerful, lightweight, and perfect for decoupling modules. By using custom events the right way, you can improve your application's architecture, modularity, and scalability.
Don't tie your classes together with direct calls — let Spring handle the communication with events.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment