yaml配置注入

yaml注入配置文件

1. 新建yaml配置文件

在Springboot项目中的resources目录下新建一个文件application.yml

2. 编写一个实体类Dog;

1
2
3
4
5
6
@Component  //注册bean到容器中
@Data
public class Dog {
private String name;
private int age;
}

3. 使用@Value给bean注入属性值

4. 再编写实体类Person

1
2
3
4
5
6
7
8
9
10
@Component
@Data
public class Person {
private String name;
private int age;
private Date birthday;
private Map<String,Object> map;
private List<Object> list;
private Dog dog;
}

5. 编写一个yaml配置

1
2
3
4
5
6
7
8
9
person:
name: 张金
age: 22
birthday: 1998/06/26
map: {k1: v1,k2: v2}
list: [111,222,333]
dog:
name: "花花"
age: 8

6. 将对象的值注入到类中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
@Data
//将配置文件中配置的每一个属性的值映射到这个组件中
//告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
//参数prefix="person":将配置文件中的person下的所有属性一一对应
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private Date birthday;
private Map<String,Object> map;
private List<Object> list;
private Dog dog;
}

7. 测试

所有值注入成功

解决Person类爆红问题,需要在pom.xml添加如下依赖:

1
2
3
4
5
6
7

<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

yaml扩展

在yaml中,我们可以使用占位符,这样可以减少我们的逻辑代码的编写

1
2
3
4
5
6
7
8
9
person:
name: 张金${random.uuid}
age: ${random.int(0,10)}
birthday: 1998/06/26
map: {k1: v1,k2: v2}
list: [111,222,333]
dog:
name: ${person.age>5?giao:xiaogiao}
age: 8

配置yaml和配置properties都可以获取到值,官方建议使用yaml,如果在某个业务中只需要获取配置文件的某个值,可以使用@Value,如果专门编写了一个JavaBean来和配置文件进行一一映射,就直接使用@ConfigurationProperties

对比

\ @ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个指定
松散绑定 (松散语法) 支持 不支持
Spel 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持

松散绑定:假设我的yaml中写的last-name,其与lastName是一样的,- 后面的字母默认是大写的。

JSR303数据校验

就是我们可以在字段上增加一层过滤验证,保证数据的合法性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;

空检查
@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 对象是否符合正则表达式的规则

导入依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.walterjwhite.java.dependencies</groupId>
<artifactId>lombok</artifactId>
<version>0.0.17</version>
</dependency>

格式正确

格式不合法

请我喝杯咖啡吧~

支付宝
微信