0 day streak
java / intermediate
Snippet

Decoupling Components with Application Events

Application events facilitate loose coupling between components. Instead of calling an email service directly from a registration service, you publish an event that interested listeners can handle independently.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public record UserRegisteredEvent(String email) {}
@Service
public class RegistrationService {
@Autowired private ApplicationEventPublisher publisher;
public void register(String email) {
// Registration logic...
publisher.publishEvent(new UserRegisteredEvent(email));
}
}
@Component
public class EmailListener {
@EventListener
public void handleUserRegistration(UserRegisteredEvent event) {
System.out.println("Sending welcome email to: " + event.email());
}
}
spring
Breakdown
1
ApplicationEventPublisher
Spring interface used to broadcast events throughout the context.
2
publishEvent
Method to send an object as an event to all registered listeners.
3
@EventListener
Annotation that marks a method as an event handler for a specific type.