SpringBoot使用Validation框架手动校验对象是否符合规则
在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()); } } } }
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)