0 day streak
java / intermediate
Snippet

Decoupling Components with Application Events

Spring Application Events allow components to communicate without direct dependencies. This follows the Observer pattern, making the system more modular and easier to extend.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
public class OrderService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void completeOrder(Order order) {
// Business logic...
eventPublisher.publishEvent(new OrderCompletedEvent(order));
}
}
@Component
public class EmailListener {
@EventListener
public void handleOrderCompleted(OrderCompletedEvent event) {
System.out.println("Sending email for order: " + event.getOrder().getId());
}
}
spring
Breakdown
1
ApplicationEventPublisher
The interface used to publish events within the Spring application context.
2
publishEvent(new OrderCompletedEvent(order))
Sends the event object to all registered listeners.
3
@EventListener
Annotation that marks a method as a listener for a specific event type.