在springboot项目中引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
伪代码
import lombok.Data; import lombok.experimental.Accessors; import javax.validation.constraints.NotNull; @Data @Accessors(chain = true) public class DemoEntity { private Long id; @NotNull private String name; }
使用
import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; public class Test4 { public static void main(String[] args) { DemoEntity entity = new DemoEntity(); entity.setId(1L); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); // 手动校验对象 Set<ConstraintViolation<DemoEntity>> violations = validator.validate(entity); if (violations.isEmpty()) { System.out.println("对象值匹配"); } else { for (ConstraintViolation<DemoEntity> violation : violations) { System.out.println(violation.getPropertyPath() + ": " + violation.getMessage()); } } } }
标签:validation,SpringBoot,violation,校验,import,violations,Validation,javax From: https://www.cnblogs.com/pxblog/p/18009822