SpringBoot:yaml注入,JSR303数据校验

公众号上线啦!
搜一搜【国服冰】
使命:尽自己所能给自学后端开发的小伙伴提供一个少有弯路的平台
回复:国服冰,即可领取我为大家准备的资料,里面包含整体的Java学习路线,电子书,以及史上最全的面试题!

一、yaml

YAML是"YAML Ain’t a Markup Language"(YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言),但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。

yaml语法采用多行缩进,对比XML格式,yaml精简、可读性高

yaml语法格式:

  1. 属性:空格 值
  2. 以缩进来控制层级关系,只要左对齐则是同一级
  3. 大小写十分敏感

二、yaml注入

以往我们属性注入有两种常用方法,一是通过Spring xml配置文件、二是通过@Value注解,下面来看看yaml和@Value的区别
直通车:Spring之IOC(DI)基于注解装配bean

1、@Value注入

Cat实体类:

package site.kexing.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

/**
 * 普通spring注解注入属性
 */
@Repository
public class Cat {
    @Value("喵喵")
    private String name;
    @Value("雌")
    private String sex;
    @Value("可星")
    private String host;
//有参无参构造、set、get、toString

Test:

package site.kexing;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import site.kexing.pojo.Cat;
import site.kexing.pojo.Dog;
import site.kexing.pojo.Person;

@SpringBootTest
class Springboot02ApplicationTests {
    @Autowired
    Cat cat;
    @Test
    void contextLoads() {
        System.out.println("@Value注入:"+cat);
    }
}

SpringBoot:yaml注入,JSR303数据校验_第1张图片

2、yaml注入

Person实体类:

package site.kexing.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;

@Repository
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private int age;
    private Boolean happy;
    private Map<String,String> address;
    private List<String> list;
//有参无参构造、set、get、toString

@ConfigurationProperties的作用是将yml中设置的属性值映射到组件中
prefix属性将yml配置绑定到该组件中

application.yml:

server:
  port: 80

person:
  name: 张三
  age: 12
  happy: true
  address: {home1: 001,home2: 002}
  list:
    - mom
    - dad
    - son

Test:

package site.kexing;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import site.kexing.pojo.Cat;
import site.kexing.pojo.Dog;
import site.kexing.pojo.Person;

@SpringBootTest
class Springboot02ApplicationTests {
    @Autowired
    Person person;
    @Test
    void contextLoads() {
        System.out.println("yaml格式@ConfigurationProperties注入:"+person);
    }
}

SpringBoot:yaml注入,JSR303数据校验_第2张图片

3、对比:

SpringBoot:yaml注入,JSR303数据校验_第3张图片

  • @ConfigurationProperties只需要写一次即可,@Value则需要对每个字段都添加
  • 松散绑定:比如我的yaml中写的 last-name,这个和 lastName 是一样的,- 后面跟着的字母默认是大写的,这就是松散绑定
  • JSR303数据校验:可以在字段是增加一层过滤器验证,可以保证数据的合法性
  • 复杂类型封装:yaml中可以封装对象,使用@value就不支持

最佳实践

  • 配置 yaml 和配置 properties 都可以获取到值时,首荐 yaml;
  • 如果在某个业务中,只需要获取配置文件中的某个值,可以使用一下@value
  • 如果有编写的JavaBean来和配置文件进行一一映射,就直接@configurationProperties

三、JSR303

添加依赖:

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
        dependency>

Person实体类:
使用@Validated 以及在需要校验的字段上增加校验注解

package site.kexing.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;

@Repository
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    private String name;
    private int age;
    private Boolean happy;
    private Map<String,String> address;
    private List<String> list;
    @Email(message = "邮箱格式不正确")
    private String email;
//有参无参构造、set、get、toString

yml:

person:
  name: 张三
  age: 12
  happy: true
  address: {home1: 001,home2: 002}
  list:
    - mom
    - dad
    - son
  email: [email protected]

Test:
SpringBoot:yaml注入,JSR303数据校验_第4张图片
如果映射错误的邮箱:
SpringBoot:yaml注入,JSR303数据校验_第5张图片

常用的校验注解

空检查
@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=) Validates that the annotated string is between min and max included.
 
日期检查
@Past           验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     	验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    	验证 String 对象是否符合正则表达式的规则
 
数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min            验证 Number 和 String 对象是否大等于指定的值  
@Max            验证 Number 和 String 对象是否小等于指定的值  
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits     验证 Number 和 String 的构成是否合法  
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
 
@Range(min=, max=) 检查数字是否介于min和max之间.
@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;
 
@Valid  递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
    
@CreditCardNumber 信用卡验证
@Email  验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
    
@URL(protocol=,host=, port=,regexp=, flags=)

你可能感兴趣的:(SpringBoot)