Use hibernate-validator to manually validate pojo properties

Sometimes we need to manually verify the pojo parameters without entering the parameters in the spring container

At the same time, I hope to use jsr-303. At this time, we can use hibernate-validator to manually verify, and hibernate-validator is the implementer of jsr-303.

pojo

public class SettleInfo {
    @NotNull
    private Integer id;
    private String name;
    private Date birth;
}

 Check code:


import com.jpush.model.SettleInfo;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

public class Client {
    public static void main(String[] args) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        SettleInfo settleInfo = new SettleInfo();
        Set<ConstraintViolation<SettleInfo>> validateSet = validator.validate(settleInfo, Default.class);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<SettleInfo> constraintViolation : validateSet) {
                System.out.println(constraintViolation.getPropertyPath().toString()+"==="+constraintViolation.getMessage());
            }
        }

    }
}

As a result, it can be found that the verification takes effect normally

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324158134&siteId=291194637