<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.3.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
package com.me.domain;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Min;
public class Student {
private Integer id;
@NotBlank
@Min(4)
private String name;
private Integer sex;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
", age=" + age +
'}';
}
}
package com.me;
import com.me.domain.Student;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
public class App {
public static void main(String[] args) {
try {
Student student = new Student();
student.setId(1);
student.setName("张三");
student.setAge(18);
student.setSex(1);
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Student>> validate = validator.validate(student);
if (validate.size() > 0) {
validate.forEach(System.out::println);
System.out.println("验证不通过");
} else {
System.out.println("验证通过");
}
}catch (Exception e){
e.printStackTrace();
}
}
}