对于最新的稳定版本,请使用 Spring Data REST 4.3.1Spring中文文档

对于最新的稳定版本,请使用 Spring Data REST 4.3.1Spring中文文档

REST 导出器在处理实体的整个过程中发出八个不同的事件:Spring中文文档

编写一个ApplicationListener

您可以对侦听此类事件的抽象类进行子类化,并根据事件类型调用相应的方法。为此,请重写相关事件的方法,如下所示:Spring中文文档

public class BeforeSaveEventListener extends AbstractRepositoryEventListener {

  @Override
  public void onBeforeSave(Object entity) {
    ... logic to handle inspecting the entity before the Repository saves it
  }

  @Override
  public void onAfterDelete(Object entity) {
    ... send a message that this entity has been deleted
  }
}

然而,这种方法需要注意的一点是,它没有根据实体的类型进行区分。你必须自己检查。Spring中文文档

编写带注释的处理程序

另一种方法是使用带批注的处理程序,该处理程序根据域类型筛选事件。Spring中文文档

要声明处理程序,请创建一个 POJO 并在其上放置注释。这表示需要检查此类的处理程序方法。@RepositoryEventHandlerBeanPostProcessorSpring中文文档

一旦找到具有此注释的 Bean,它就会遍历公开的方法并查找与相关事件相对应的注释。例如,要处理带注释的 POJO 中不同类型的域类型的实例,您可以按如下方式定义类:BeanPostProcessorBeforeSaveEventSpring中文文档

@RepositoryEventHandler (1)
public class PersonEventHandler {

  @HandleBeforeSave
  public void handlePersonSave(Person p) {
    // … you can now deal with Person in a type-safe way
  }

  @HandleBeforeSave
  public void handleProfileSave(Profile p) {
    // … you can now deal with Profile in a type-safe way
  }
}
1 可以使用 (例如) 缩小此处理程序应用的类型范围。@RepositoryEventHandler(Person.class)

您感兴趣的事件的域类型由带批注方法的第一个参数的类型确定。Spring中文文档

要注册事件处理程序,请使用 Spring 的构造型之一标记该类(以便 或 可以拾取它),或者在 .然后,在 中创建的 that 检查 Bean 中的处理程序,并将它们连接到正确的事件。下面的示例演示如何为类创建事件处理程序:@Component@SpringBootApplication@ComponentScanApplicationContextBeanPostProcessorRepositoryRestMvcConfigurationPersonSpring中文文档

@Configuration
public class RepositoryConfiguration {

  @Bean
  PersonEventHandler personEventHandler() {
    return new PersonEventHandler();
  }
}
Spring Data REST 事件是自定义的 Spring 应用程序事件。默认情况下,Spring 事件是同步的,除非它们跨边界重新发布(例如发出 WebSocket 事件或交叉到线程中)。
1 可以使用 (例如) 缩小此处理程序应用的类型范围。@RepositoryEventHandler(Person.class)
Spring Data REST 事件是自定义的 Spring 应用程序事件。默认情况下,Spring 事件是同步的,除非它们跨边界重新发布(例如发出 WebSocket 事件或交叉到线程中)。