JSR-303简单使用

一、关于JSR

JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。

二、关于 JSR-303

JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

三、Hibernate 对其实现

Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

四、简单介绍

在这里插入图片描述

五、补充

Hibernate 中填充一部分
在这里插入图片描述

六、springBoot中的实现

  1. 引入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    
  2. 使用

    person:
      name: laoyao
      age: 18
      happy: false
      birth: 1900/1/1
      maps:
        k1: v1
        k2: v2
    # 也可以使用  maps: {k1=v1, k2=v2}
      lists:
        - code
        - game
        - girl
      dog:
        name: 旺财
        age: 12
    
    @Component
    @Data
    @ConfigurationProperties(prefix = "person")
    @Validated	//使用这个注释后,才能使用@Email
    public class Person {
        @Email	//说明name只能为email格式
        private String name;
        @NotNull //非空
        private Integer age;
        private Boolean happy;
        private Date birth;
        private Map<String,Object> maps;
        private List<Object> lists;
        private Dog dog;
    }
    
  3. 运行

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'person' to cn.laoyao.pojo.Person failed:
Property: person.name
Value: "laoyao"
Origin: class path resource [application.yaml] - 6:9
Reason: 不是一个合法的电子邮件地址
posted @ 2022-08-04 17:28  z-laoyao  阅读(112)  评论(0编辑  收藏  举报