文章目录
需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
创建校验对象Validator
测试的实体类
//创建实体类,定义属性及方法,供校验测试
@Data
public class Person {
@NotBlank(message = "名称不能为空")
@Size(max = 255, message = "名称长度不能超过255个字符")
private String name;
private int age;
}
校验案例
public static void main(String[] args) {
// 校验的对象
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
// 需要校验的数据
Person person = new Person();
// 校验结果,如果有校验未通过的则返回校验未通过的信息
Set<ConstraintViolation<Person>> validate = validator.validate(person);
// 经校验信息转成list并打印
System.out.println("===" + validate.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()));
}
创建Validator工具类
public class ValidationUtil {
private static final Validator validator;
static {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
validator = factory.getValidator();
}
}
public static <T> List<String> validate(T t) {
return validator.validate(t).stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
}
}