Event handling
Event handler
Event handlers are components that act on incoming events. They are often used in external systems to get notifications about things that happened. In reaction to that, event handlers can execute their own logic. Usually, this involves updating view models or forwarding updates to other components.
See below for an example of a customer event handler:
public class CustomerEventHandler {
@HandleEvent
public void handle(CustomerCreated event) {
// send welcome email...
}
}
Methods annotated with @HandleEvent
will get triggered when the corresponding event occurs.
Event handlers are often used in external systems for updating view models or sending out emails. They are also used for implementing a saga-pattern.
Publishing events
Although events are published by command handlers, EasySourcing also provides an EventGateway
where you can publish events directly. This can be usefull when publishing events from other components or when testing your event handlers.
To publish an event, call the publish()
method on the EventGateway
:
public class SomeService {
private EventGateway eventGateway;
public void sendEvent() {
CustomerCreated event = CustomerCreated.builder()
.customerId("cust-123")
.firstName("John")
.lastName("Doe")
.build();
eventGateway.publish(event);
}
}
Spring Boot
When using Spring Boot, you can just autowire an instance of EventGateway
.