Spring Events
Report an event without directly coupling classes
Sometimes one part of the application needs to say “something happened,” and another part needs to react. You can call the required service directly, but then the sender starts knowing about the receiver. Spring Events lets you loosen that coupling.
record OrderCreated(long orderId) {
}
@Service
class OrderService {
private final ApplicationEventPublisher publisher;
OrderService(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
void create(long orderId) {
publisher.publishEvent(new OrderCreated(orderId));
}
}
@Component
class OrderCreatedListener {
@EventListener
void on(OrderCreated event) {
System.out.println("Order: " + event.orderId());
}
}
OrderService publishes the fact that an order was created,
but it does not know who will subscribe to it. The listener declares interest in the event with
@EventListener and receives the event object as an argument.
These are in-application events
Spring Events work inside one ApplicationContext.
They are not a replacement for Kafka, RabbitMQ, or another message broker.
By default, handlers are called synchronously, so publishing the event and running the listener
happen in the same execution thread.
An event should describe a fact.
A name such as
OrderCreated communicates the idea better
than a command such as SendEmailNow: the sender reports what happened,
and receivers decide for themselves whether they need to react.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in