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