Spring Events Example
Spring Events Example
Spring Data JDBC triggers events that get published to any matching ApplicationListener beans in the application context. For example, the following listener gets invoked before an aggregate gets saved:@Bean
public ApplicationListener<BeforeSaveEvent<Object>> loggingSaves() {
return event -> {
Object entity = event.getEntity();
LOG.info("{} is getting saved.";
};
}
If you want to handle events only for a specific domain type you may derive your listener from AbstractRelationalEventListener and overwrite one or more of the onXXX methods, where XXX stands for an event type. Callback methods will only get invoked for events related to the domain type and their subtypes so you don’t require further casting.
public class PersonLoadListener extends AbstractRelationalEventListener<Person> {
@Override
protected void onAfterLoad(AfterLoadEvent<Person> personLoad) {
LOG.info(personLoad.getEntity());
}
}
The following table describes the available events:
BeforeDeleteEvent
Before an aggregate root gets deleted.AfterDeleteEvent
After an aggregate root gets deleted.
BeforeConvertEvent
Before an aggregate root gets saved (that is, inserted or updated but after the decision about whether if it gets updated or deleted was made).
BeforeSaveEvent
Before an aggregate root gets saved (that is, inserted or updated but after the decision about whether if it gets updated or deleted was made).
AfterSaveEvent
After an aggregate root gets saved (that is, inserted or updated).
AfterLoadEvent
After an aggregate root gets created from a database ResultSet and all its property get set.
Comments
Post a Comment