该栏目会系统的介绍 SpringBoot 的知识体系,共分为基础部分、源代码和综合实例等模块
简介
- :是一种标记语言,非常适合用在以数据为中心的配置文件
基本语法
- key: value:键值对之间有空格
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用 Tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果加了,单引号会转义,双引号不会转义
数据类型表示
字面量
:单个的,不可再分的值。date、boolean、string、number、null
key: value
对象
:键值对的集合。map、hash、set、object
# 行内写法
key: {k1:v1,k2:v2}
# 普通写法
key:
k1: v1
k2: v2
数组
:键值对的集合。map、hash、set、object
# 行内写法
key: [v1,v2]
# 普通写法
key:
- v1
- v2
- v3
配置提示
<!--引入配置处理器依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--maven打包时不需要导入配置处理器-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
案例
1、@ConfigurationProperties 方式
用户实体类
@Configuration
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
private String name;
private Integer age;
private Date birth;
private Boolean boss;
private Order pet;
private String[] interests;
private List<String> animals;
private Set<Double> salaries;
private Map<String, Object> scores;
}
宠物实体类
@Data
class Pet {
private String name;
private Double weight;
}
配置文件
person:
name: Near
age: 18
boss: true
birth: 2021/12/12 20:12:33
pet: {name: Peter,weight: 18}
interests: ['阅读','看电影','打代码']
animals:
- dog
- cat
salaries: [12000,30000,42000]
scores:
enight: 150
math: 130
2、@Value 方式
订单实体类
@Data
@Component
public class Order {
@Value(value = "${order.orderNo}")
private String orderNo;
@Value("${order.totalPrice}")
private double totalPrice;
}
配置文件
order:
orderNo: 20210527213134
totalPrice: 123.4