有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将组动态设置为Spring验证程序

我正在实现一个RESTAPI,在这里我必须对请求体进行一些验证。基于Json中名为“type”的字段中定义的值,我想动态地将组设置为Spring Validator

通过查看文档,我找到的唯一解决方案是在方法签名处设置@Validated注释,并对要传递给它的组进行硬编码

我从javax中找到了一个使用验证器的替代解决方案。验证包,目前我的代码如下所示:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<EnterpriseResource>> constraintViolationSet = new HashSet<>();
    if (isTypeEnterprise(enterpriseResource, EnterpriseTypeEnum.BUYER)) {
      constraintViolationSet = validator.validate(enterpriseResource, BuyerEnterprise.class);
    }
    if (isTypeEnterprise(enterpriseResource, EnterpriseTypeEnum.PROVIDER)) {
      constraintViolationSet = validator.validate(enterpriseResource, ProviderEnterprise.class);
    }
    if (!constraintViolationSet.isEmpty()) {
      log.info("=========================ERRORS: {}", constraintViolationSet.toString());
      throw new ConstraintViolationException(constraintViolationSet);
    }

是否有任何变通方法可以让我使用Spring本机验证程序实例获得相同的行为


共 (1) 个答案

  1. # 1 楼答案

    下面是一个帮助器类,它使用spring MVC validator,并允许您以编程方式指定验证组

    @Component
    public class ValidatorTool {
       private static final Method method = ValidatorTool.class.getMethods()[0];
    
       @Autowired
       @Qualifier("mvcValidator")
       private org.springframework.validation.Validator validator;
    
    
       @SneakyThrows
       public void validate(Object object, Object... validationGroups) {
           DataBinder binder = new DataBinder(object);
           binder.addValidators(validator);
           binder.validate(validationGroups);
           BindingResult br = binder.getBindingResult();
    
    
           if (br.hasErrors()) {
              log.info("Validation of {} failed: {}", object.getClass(), br.getAllErrors());
              throw new MethodArgumentNotValidException(
                    new MethodParameter(method, 0),
                    br);
           }
       }
    }