有时我们需要手动校验pojo参数,而不在spring的容器内通过入参这种方式

同时希望能使用jsr-303 ,这时我们可以使用hibernate-validator 手动校验,并且hibernate-validator  就是jsr-303的实现者

pojo

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

 校验代码:


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());
            }
        }

    }
}

结果,可以发现校验正常生效

利用hibernate-validator 手动校验pojo属性-LMLPHP

03-15 05:31