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 inMongoTemplate
insert
,insertList
, andsave
operations before the object is converted to aDocument
by aMongoConverter
. -
onBeforeSave
: Called inMongoTemplate
insert
,insertList
, andsave
operations before inserting or saving theDocument
in the database. -
onAfterSave
: Called inMongoTemplate
insert
,insertList
, andsave
operations after inserting or saving theDocument
in the database. -
onAfterLoad
: Called inMongoTemplate
find
,findAndRemove
,findOne
, andgetCollection
methods after theDocument
has been retrieved from the database. -
onAfterConvert
: Called inMongoTemplate
find
,findAndRemove
,findOne
, andgetCollection
methods after theDocument
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 .
|