How to combine JSR-303 and Spring Validator class in a service layer?

≯℡__Kan透↙ 提交于 2019-11-29 02:31:45

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

An possible implementation would be

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) {
      // ...
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!