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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Componentpublic class OrderService {@Autowiredprivate ApplicationEventPublisher eventPublisher;public void completeOrder(Order order) {// Business logic...eventPublisher.publishEvent(new OrderCompletedEvent(order));}}@Componentpublic class EmailListener {@EventListenerpublic 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.