JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator 是 Bean Validation 的参考实现 。Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理,如:
    导入依赖:

    1. <!--spring boot-jsr303数据校验需要的依赖-->
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-validation</artifactId>
    5. </dependency>
    @Component
    @ConfigurationProperties(prefix = "person")
    @Validated
    public class Person {
        @Email(message = "这不是一个合法的邮箱号")
        private String email;
        @NotNull(message = "名字不能为空")
        private String name;
        @Max(value = 40 ,message = "年龄不能超过40岁")
        private Integer age;
    
       //构造方法和getXxx、setXxx方法
    
    }
    
    person:
      email: "2691397780@qq.com"
      name: "阿离"
      age: 18
    
    @SpringBootApplication
    public class Application {
        @Autowired
        Person person;
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    

    运行结果:
    image.png

    空检查
    @Null       验证对象是否为null
    @NotNull    验证对象是否不为null, 无法查检长度为0的字符串
    @NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
    @NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
    Booelan检查
    @AssertTrue     验证 Boolean 对象是否为 true  
    @AssertFalse    验证 Boolean 对象是否为 false  
    
    长度检查
    @Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
    @Length(min=, max=) string is between min and max included.
    
    日期检查
    @Past       验证 Date 和 Calendar 对象是否在当前时间之前  
    @Future     验证 Date 和 Calendar 对象是否在当前时间之后  
    @Pattern    验证 String 对象是否符合正则表达式的规则
    
    ......
    
    除此以外,我们还可以自定义一些数据校验规则