本文介绍了如何在服务层中结合JSR-303和Spring Validator类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些模型课

public class Account {

    @Email
    private String email;

    @NotNull
    private String rule;
}

和spring-validator

and spring-validator

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中描述这些规则吗?

Can I add to my validation process constraints @Email, @NotNull (JSR-303) and don't describe these rules in AccountValidator?

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

I know how works @Valid in spring-controllers, but what's about service layer? Is it possible? How to do such kind of validation in a proper way? May I should use Hibernate Validator?

推荐答案

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

Spring provides an Adapter to merge both validation APIs.See the current Spring JavaDoc for more information.

可能的实现方式是

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) {
      // ...
  }
}

这篇关于如何在服务层中结合JSR-303和Spring Validator类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:28