5

我有一些模型课

public class Account {

    @Email
    private String email;

    @NotNull
    private String rule;
}

和弹簧验证器

public class AccountValidator implements Validator {

    @Override
    public boolean supports(Class aClass) {
        return Account.class.equals(aClass);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        Account account = (Account) obj;
        ValidationUtils.rejectIfEmpty(errors, "email", "email.required");
        ValidationUtils.rejectIfEmpty(errors, "rule", "rule.required");

        complexValidateRule(account.getRule(), errors);
    }

    private void complexValidateRule(String rule, Errors errors) {
        // ...
    }
}

我在我的服务中运行

AccountValidator validator = new AccountValidator();
Errors errors = new BeanPropertyBindingResult(account, "account");
validator.validate(account, errors);

我可以添加到我的验证过程约束 @Email、@NotNull (JSR-303) 并且不在 AccountValidator 中描述这些规则吗?

我知道 @Valid 在 spring-controllers 中是如何工作的,但是关于服务层呢?可能吗?如何以适当的方式进行这种验证?我可以使用 Hibernate Validator 吗?

4

1 回答 1

10

Spring 提供了一个适配器来合并两个验证 API。有关更多信息,请参阅当前的 Spring JavaDoc

一个可能的实现是

public class AccountValidator implements Validator {

  private final SpringValidatorAdapter validator;

  public AccountValidator(SpringValidatorAdapter validator) {
      super();
      this.validator = validator;
  }

  @Override
  public boolean supports(Class aClass) {
      return Account.class.equals(aClass);
  }

  @Override
  public void validate(Object obj, Errors errors) {

      //jsr303
      validator.validate(obj, errors);

      //custom rules
      Account account = (Account) obj;
      complexValidateRule(account.getRule(), errors);
  }

  private void complexValidateRule(String rule, Errors errors) {
      // ...
  }
}
于 2014-11-04T11:05:47.770 回答