对于最新的稳定版本,请使用 Spring Data REST 4.4.0! |
事件
REST 导出器在使用实体的整个过程中会发出 8 个不同的事件:
编写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
}
}
但是,此方法需要注意的一点是,它不根据实体的类型进行区分。你必须自己检查一下。
编写带注释的处理程序
另一种方法是使用带注释的处理程序,该处理程序根据域类型筛选事件。
要声明处理程序,请创建一个 POJO 并将@RepositoryEventHandler
注释。这告诉BeanPostProcessor
需要检查此类的处理程序方法。
一旦BeanPostProcessor
查找具有此 Comments 的 Bean,它会迭代公开的方法并查找与相关事件相对应的 Comments。例如,要处理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
}
}
1 | 可以使用 (例如) 来缩小此处理程序适用的类型@RepositoryEventHandler(Person.class) . |
您感兴趣的事件的域类型由带注释的方法的第一个参数的类型确定。
要注册你的事件处理程序,请使用 Spring 的@Component
stereotypes (以便它可以被@SpringBootApplication
或@ComponentScan
) 或在ApplicationContext
.然后BeanPostProcessor
在RepositoryRestMvcConfiguration
检查 Bean 中的处理程序,并将它们连接到正确的事件。以下示例说明如何为Person
类:
@Configuration
public class RepositoryConfiguration {
@Bean
PersonEventHandler personEventHandler() {
return new PersonEventHandler();
}
}
Spring Data REST 事件是自定义的 Spring 应用程序事件。默认情况下, Spring 事件是同步的,除非它们跨边界重新发布(例如发出 WebSocket 事件或跨越线程)。 |