Validation

可以在 Spring Data REST 中通过两种方式注册 Validator 实例:通过 Bean 名称连接它或手动注册验证器。对于大多数情况,简单的 Bean 名称前缀样式就足够了。

There are two ways to register a Validator instance in Spring Data REST: wire it by bean name or register the validator manually. For the majority of cases, the simple bean name prefix style is sufficient.

为了告诉 Spring Data REST 你希望在特定事件中分配一个特定的 Validator,请使用有问题的事件作为 Bean 名称的前缀。例如,要在将新的 Person 类实例保存到存储库之前对其进行验证,需要在 ApplicationContext 中声明一个 Validator<Person> 实例,其 Bean 名称为 beforeCreatePersonValidator。由于 beforeCreate 前缀与已知的 Spring Data REST 事件匹配,因此该验证器已连接到正确的事件。

In order to tell Spring Data REST you want a particular Validator assigned to a particular event, prefix the bean name with the event in question. For example, to validate instances of the Person class before new ones are saved into the repository, you would declare an instance of a Validator<Person> in your ApplicationContext with a bean name of beforeCreatePersonValidator. Since the beforeCreate prefix matches a known Spring Data REST event, that validator is wired to the correct event.

Assigning Validators Manually

如果你不想使用 Bean 名称前缀方法,则需要将验证器实例注册到在正确事件后调用验证器的 Bean。在实现 RepositoryRestConfigurer 的配置中,覆盖 configureValidatingRepositoryEventListener 方法并在 ValidatingRepositoryEventListener 上调用 addValidator,传递触发此验证器的事件和验证器实例。以下示例显示了如何执行此操作:

If you would rather not use the bean name prefix approach, you need to register an instance of your validator with the bean whose job it is to invoke validators after the correct event. In your configuration that implements RepositoryRestConfigurer, override the configureValidatingRepositoryEventListener method and call addValidator on the ValidatingRepositoryEventListener, passing the event on which you want this validator to be triggered and an instance of the validator. The following example shows how to do so:

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