事件
编写 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,它会遍历公开的方法并查找与相关事件对应的注解。例如,要在带注解的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
}
}
| 1 | 可以通过使用(例如) @RepositoryEventHandler(Person.class) 来缩小此处理器适用的类型范围。 |
您感兴趣的领域类型事件将由带注解方法的第一个参数的类型决定。
要注册您的事件处理器,要么用Spring的 @Component 派生注解之一标记该类(以便它可以被 @SpringBootApplication 或 @ComponentScan 发现),要么在您的 ApplicationContext 中声明一个带注解的bean实例。然后,在 RepositoryRestMvcConfiguration 中创建的 BeanPostProcessor 会检查该bean以查找处理器并将它们连接到正确的事件。以下示例展示了如何为 Person 类创建事件处理器
@Configuration
public class RepositoryConfiguration {
@Bean
PersonEventHandler personEventHandler() {
return new PersonEventHandler();
}
}
| Spring Data REST事件是自定义的Spring应用程序事件。默认情况下,Spring事件是同步的,除非它们跨边界重新发布(例如发出WebSocket事件或跨线程)。 |