SpringBoot 除了可以在类路径下创建一个
application.properties
作为全局配置文件外,还兼容另外一种 yaml 格式的配置文件。
yaml
YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。
非常适合用来做以数据为中心的配置文件
基本语法
● key: value;kv之间有空格
● 大小写敏感
● 使用缩进表示层级关系
● 缩进不允许使用tab,只允许空格
● 缩进的空格数不重要,只要相同层级的元素左对齐即可
● '#‘表示注释
● 字符串无需加引号,如果要加,’'与""表示字符串内容 会被 转义/不转义
数据类型
● 字面量:单个的、不可再分的值。date、boolean、string、number、null
k: v
● 对象:键值对的集合。map、hash、set、object
# 行内写法
k: {k1:v1,k2:v2,k3:v3}
#或
k:
k1: v1
k2: v2
k3: v3
● 数组:一组按次序排列的值。array、list、queue
#行内写法: k: [v1,v2,v3]
#或者
k:
- v1
- v2
- v3
示例
@Component // 作为组件加入Spring 容器
@ConfigurationProperties(prefix = "person") // 绑定配置文件中的 person 开头的配置属性
@Data
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Map<String, Object> score;
private Set<Double> salarys;
private Map<String, List<Pet>> allPets;
}
@Data
public class Pet {
private String name;
private Double weight;
}
使用 yml 表示,application.yml
配置文件中:
# yaml表示以上对象
person:
userName: zhangsan
boss: false
birth: 2019/12/12 20:12:33
age: 18
pet:
name: tomcat
weight: 23.4
interests: [篮球,游泳]
animal:
- jerry
- mario
score:
english:
first: 30
second: 40
third: 50
math: [131,140,148]
chinese: {first: 128,second: 136}
salarys: [3999,4999.98,5999.99]
allPets:
sick:
- {name: tom}
- {name: jerry,weight: 47}
health: [{name: mario,weight: 47}]
启动SpringBoot应用,测试
package com.rpm.springboot;
import com.rpm.springboot.bean.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
// 从容器中获取 Person 对象
Person bean = run.getBean(Person.class);
System.out.println(bean);
}
}
配置文件的加载优先级
如果同时配置了 application.properties
和 application.yml
文件,SpringBoot 会优先加载 application.properties
自定义配置类绑定提示
在 pom.xml中 引入 SpringBoot 的配置处理器依赖,即可在编写 自定义配置时,自动提示配置属性
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
该功能只是在开发阶段使用,打包项目时,无需参与打包,在打包插件中做排除打包配置
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>