如何手动触发对象的自定义带注释的验证规则?

时间:2019-01-17 18:24:04

标签: java spring-boot bean-validation

我需要手动或在将json字符串转换为对象的过程中触发对对象的自定义验证器。

我的dto如下:

@NotNullable.List({
    @NotNullable(enumMessage = RequiredFieldErrors.NAME_REQUIRED, fieldName = "info.personName")
//More
})

@SpecificValue.List({
    @SpecificValue(enumMessage = BusinessErrors.CONFIDENTIALITY_REQUESTED, fieldName = "info.personName.confidentialityRequested", value = ConstantValue.CONFIDENTIALITY_VALUES)
//More
})

@DependentField.List({
    @DependentField(
            parentFieldName = "info.personDemographics.ssnUnknown", 
            parentFieldValue = "false", 
            childFieldNames = {"info.personDemographics.ssn"},
            childFieldValues = {ConstantValue.SSN_PATTERN},
            includeChildValues = true,
            enumMessage = RequiredFieldErrors.PAYEE_SSN_MUST_BE_NUMERIC)
//More
})

public class MyClass implements Serializable {
    private static final long serialVersionUID = 1L;
    @SpecificValue(enumMessage = BusinessErrors.SOURCE_ID_INVALID, value = ConstantValue.SOURCE_ID)
    private String sourceId;
    @NotNullable(enumMessage = RequiredFieldErrors.INFO_REQUIRED)
    private PersonType info;
//More
}

在上面的代码中,PersonType由其他对象类型组成。再次验证这些对象。

这样工作正常。

@RequestMapping(value = "/api/rest/uploadefile", method = {RequestMethod.POST}
public ResponseEntity<Object> upload1(@Valid @RequestBody MyClass request, BindingResult bindingResult, HttpServletRequest request) {        
     if(bindingResult.hasErrors()) {
          throw new FieldValidationException(Contstants.INVALID_REQUEST, errors);
    }
}

我需要获取json请求作为字符串。我知道@Valid @RequestPart ....对于多部分/混合类型可以正常工作。我想要这样的东西:

@RequestMapping(value = "/api/rest/uploadefile", method = {RequestMethod.POST}, headers = {"content-type=multipart/form-data"})
public ResponseEntity<Object> upload1(@RequestPart(value = "request", required = true) String request, @RequestPart(value = "file", required = true) List<MultipartFile> file, Errors errors) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        MyClass myClass = mapper.readValue(request, MyClass.class);
        ValidationUtils.invokeValidator(validator1, myClass, errors);
        if(errors.hasErrors()) {
                  throw new FieldValidationException(Contstants.INVALID_REQUEST, errors);
        }
}

我尝试了springframework验证器和javax jsr验证器。他们俩都没有工作。我收到以下错误消息:

class java.lang.IllegalStateException JSR-303 validated property 'info.personName' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access

对于以下请求:

curl -i -X POST -myURL -H "Authorization: ABC" -F request={} -F file=@view.pdf

我的验证器如下实现javax.validation.ConstraintValidator:

public class DependentFieldValidator implements ConstraintValidator<DependentField, Object> {
 //My code
}

2 个答案:

答案 0 :(得分:2)

您用于验证的Errors不是应该使用的 Errors

如果您将使用手动创建的Errors,它将起作用:

BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(myClass, "myClass");
ValidationUtils.invokeValidator(validator, myClass, bindingResult);

请注意,BeanPropertyBindingResult实现了Errors

答案 1 :(得分:0)

由于我在MyClass或其字段上具有基于注释的验证器的不同类型,因此我仅按以下方式使用:

//org.springframework.validation.SmartValidator
@Autowired
SmartValidator smartValidator
public ResponseEntity<ResponseType> generateResponseExample(@RequestPart(value = "jsonString", required = true) String jsonString, @RequestPart(value = "file", required = true) List<MultipartFile> file){
  //Custom deserializer i did here but not relevant to this question, extra info
  ObjectMapper mapper = new ObjectMapper();
  SimpleModule module = new SimpleModule();
  module.addDeserializer(String.class, new StringDeserializer());
  mapper.registerModule(module);
  MyClass myClass = mapper.readValue(jsonString, MyClass.class);
  BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(myClass, "myClass");
  //This triggers all the annotation of class
  smartValidator.validate(myClass, bindingResult, MyClass.annotationgroup1.class);
  if (bindingResult.hasErrors()) {
        throw new FieldValidationException("Field validation error!", bindingResult);
  }
  //more work..
  return new ResponseEntity<>();
}