Lifecycle Events

The MongoDB mapping framework includes several org.springframework.context.ApplicationEvent events that your application can respond to by registering special beans in the ApplicationContext. Being based on Spring’s ApplicationContext event infrastructure enables other products, such as Spring Integration, to easily receive these events, as they are a well known eventing mechanism in Spring-based applications.

To intercept an object before it goes through the conversion process (which turns your domain object into a org.bson.Document), you can register a subclass of AbstractMongoEventListener that overrides the onBeforeConvert method. When the event is dispatched, your listener is called and passed the domain object before it goes into the converter. The following example shows how to do so:

public class BeforeConvertListener extends AbstractMongoEventListener<Person> {
  @Override
  public void onBeforeConvert(BeforeConvertEvent<Person> event) {
    ... does some auditing manipulation, set timestamps, whatever ...
  }
}

To intercept an object before it goes into the database, you can register a subclass of org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener that overrides the onBeforeSave method. When the event is dispatched, your listener is called and passed the domain object and the converted com.mongodb.Document. The following example shows how to do so:

public class BeforeSaveListener extends AbstractMongoEventListener<Person> {
  @Override
  public void onBeforeSave(BeforeSaveEvent<Person> event) {
    … change values, delete them, whatever …
  }
}

Declaring these beans in your Spring ApplicationContext causes them to be invoked whenever the event is dispatched.

The following callback methods are present in AbstractMappingEventListener:

  • onBeforeConvert: Called in MongoTemplate insert, insertList, and save operations before the object is converted to a Document by a MongoConverter.

  • onBeforeSave: Called in MongoTemplate insert, insertList, and save operations before inserting or saving the Document in the database.

  • onAfterSave: Called in MongoTemplate insert, insertList, and save operations after inserting or saving the Document in the database.

  • onAfterLoad: Called in MongoTemplate find, findAndRemove, findOne, and getCollection methods after the Document has been retrieved from the database.

  • onAfterConvert: Called in MongoTemplate find, findAndRemove, findOne, and getCollection methods after the Document has been retrieved from the database was converted to a POJO.

Lifecycle events are only emitted for root level types. Complex types used as properties within a document root are not subject to event publication unless they are document references annotated with @DBRef.