简体   繁体   English

使用ConstraintValidator进行Spring DTO验证

[英]Spring DTO validation using ConstraintValidator

The DTO that I use is annotated with javax.validation annotations 我使用的DTO使用javax.validation注释进行注释

For example 例如

@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentDTO {

@NotEmpty
private String name;

@Positive
private Long studentId;

}

What if I have to validate using ConstraintValidator for StudentDTO 如果我必须使用ConstraintValidator为StudentDTO验证该怎么办?

Spring MVC has the ability to automatically validate @Controller inputs. Spring MVC能够自动验证@Controller输入。 In previous versions it was up to the developer to manually invoke validation logic. 在以前的版本中,开发人员需要手动调用验证逻辑。

But in your case , you are trying to validate a DTO object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator. 但在您的情况下,您正在尝试验证DTO对象,在这种情况下,springboot可能不会自动将验证器绑定到您的模型并调用验证器。因此,在这种情况下,您需要手动将对象绑定到验证器。

or you can manually invoke the validator on a bean like : 或者您可以手动调用bean上的验证器,如:

@AutoWired
Validator validator;
...

validator.validate(book);

You can define a custom validator in springboot for model classes if you want and use annotations : 如果需要和使用注释,可以在springboot中为模型类定义自定义验证器:

@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
    String message() default "Invalid data";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and then define a validator class like : 然后定义一个验证器类,如:

public class CustomDataValidator implements
  ConstraintValidator<CustomDataConstraint, String> {

    @Override
    public void initialize(CustomDataConstraint data) {
    }

    @Override
    public boolean isValid(String field,
      ConstraintValidatorContext cxt) {
        return field!= null;
    }

}

Your validator class must implement the ConstraintValidator interface and must implement the isValid method to define the validation rules, define the validation rules can be anything as you wish.Then, you can simply add the annotation to your field like : 您的验证器类必须实现ConstraintValidator接口,并且必须实现isValid方法来定义验证规则,可以根据需要定义验证规则。然后,您只需将注释添加到字段中,如:

@CustomDataConstraint 
private String name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM