验证
在 Spring Data REST 中注册 Validator 实例有两种方式:通过 Bean 名称进行装配或手动注册验证器。对于大多数情况,简单的 Bean 名称前缀方式就足够了。
为了告知 Spring Data REST 您希望将某个 Validator 分配给特定事件,请在 Bean 名称前加上相关事件的前缀。例如,要在新的 Person 实例保存到仓库之前对其进行验证,您可以在 ApplicationContext 中声明一个 Validator<Person> 实例,其 Bean 名称为 beforeCreatePersonValidator。由于 beforeCreate 前缀与已知的 Spring Data REST 事件匹配,该验证器将被装配到正确的事件。
手动分配验证器
如果您不想使用 Bean 名称前缀方法,则需要将验证器实例注册到负责在正确事件发生后调用验证器的 Bean。在实现 RepositoryRestConfigurer 的配置中,覆盖 configureValidatingRepositoryEventListener 方法并在 ValidatingRepositoryEventListener 上调用 addValidator,传入您希望此验证器触发的事件以及验证器实例。以下示例显示了如何操作
@Override
void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
v.addValidator("beforeSave", new BeforeSaveValidator());
}