跳到主要内容

事件

DeepSeek V3 中英对照 Events

REST 导出器在处理实体的过程中会发出八种不同的事件:

编写 ApplicationListener

你可以子类化一个抽象类来监听这些类型的事件,并根据事件类型调用适当的方法。为此,需要重写相关事件的方法,如下所示:

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
}
}
java

然而,需要注意的是,这种方法并不会根据实体的类型进行区分。你需要自行进行检查。

编写带注释的事件处理程序

另一种方法是使用注解处理器(annotated handler),它根据领域类型来过滤事件。

要声明一个处理器,创建一个 POJO 并在其上放置 @RepositoryEventHandler 注解。这会告诉 BeanPostProcessor 需要检查该类以查找处理器方法。

BeanPostProcessor 发现带有此注解的 bean 时,它会遍历暴露的方法,并查找与相关事件对应的注解。例如,为了在一个带注解的 POJO 中处理不同类型的领域类型的 BeforeSaveEvent 实例,你可以如下定义你的类:

@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
}
}
java
  • 可以通过使用(例如)@RepositoryEventHandler(Person.class) 来缩小此处理程序适用的类型范围。

你感兴趣的事件域类型由注解方法的第一个参数类型决定。

要注册您的事件处理程序,可以使用 Spring 的 @Component 系列注解之一标记类(以便它能够被 @SpringBootApplication@ComponentScan 扫描到),或者在 ApplicationContext 中声明一个注解的 bean 实例。然后,在 RepositoryRestMvcConfiguration 中创建的 BeanPostProcessor 会检查该 bean 的处理程序,并将它们连接到正确的事件上。以下示例展示了如何为 Person 类创建一个事件处理程序:

@Configuration
public class RepositoryConfiguration {

@Bean
PersonEventHandler personEventHandler() {
return new PersonEventHandler();
}
}
java
备注

Spring Data REST 事件是定制的 Spring 应用事件。默认情况下,Spring 事件是同步的,除非它们跨边界重新发布(例如发出 WebSocket 事件或跨入线程)。