验证

在 Spring Data REST 中,有两种方式注册一个 Validator 实例:通过 bean 名称进行注入,或手动注册验证器。在大多数情况下,简单的 bean 名称前缀风格就已足够。spring-doc.cadn.net.cn

为了让 Spring Data REST 知道你希望将某个特定的 Validator 分配给某个特定事件,请在该 Bean 名称前加上相应事件的前缀。例如,若要在将新的 Person 实例保存到仓库之前对其进行验证,你可以在 Validator<Person> 中声明一个 ApplicationContext 的实例,并将其 Bean 名称设为 beforeCreatePersonValidator。由于 beforeCreate 前缀与 Spring Data REST 中已知的事件相匹配,该验证器就会被自动绑定到正确的事件上。spring-doc.cadn.net.cn

手动分配验证器

如果你不想使用 bean 名称前缀的方式,则需要将你的验证器实例注册到负责在特定事件发生后调用验证器的 bean 中。在你实现 RepositoryRestConfigurer 的配置类中,重写 configureValidatingRepositoryEventListener 方法,并在 addValidator 上调用 ValidatingRepositoryEventListener 方法,传入你希望触发该验证器的事件以及验证器的实例。以下示例展示了如何实现这一点:spring-doc.cadn.net.cn

@Override
void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
  v.addValidator("beforeSave", new BeforeSaveValidator());
}