监听MongoDB的生命周期,只需重写org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener的子类,并在SpringApplicationContext中声明这些bean,这样在分派事件时会调用它们。例如:

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

AbstractMappingEventListener中提供了以下回调方法:

方法 描述
onBeforeConvert 调用MongoTemplateinsertinsertListsave操作,在通过MongoConverter将对象转换为文档之前的处理。
onBeforeSave 调用MongoTemplateinsertinsertListsave操作,在数据库中插入或保存文档之前的处理。
onAfterSave 调用MongoTemplateinsertinsertListsave操作,在数据库中插入或保存文档之后的处理。
onAfterLoad 调用MongoTemplate中的findfindAndRemovefindOnegetCollection方法,从数据库检索文档后的处理。
onAfterConvert 调用MongoTemplate中的findfindAndRemovefindOnegetCollection方法,从数据库检索文档被转换为POJO后的处理。




相关文章:

  • 2021-12-12
  • 2021-11-13
  • 2022-12-23
  • 2021-05-18
  • 2022-12-23
  • 2021-09-11
  • 2021-09-20
猜你喜欢
  • 2021-11-18
  • 2021-09-03
  • 2021-10-17
  • 2021-09-14
  • 2021-08-25
  • 2022-02-21
  • 2021-09-15
相关资源
相似解决方案