SpringBoot 5. 配置文件
1. yaml 文件
适合用来做以数据为中心的配置文件。
1.1 基本语法
- key: value
- 大小写敏感
- 使用缩进表示层级关系
#
表示注释- 字符串无需加引号,
''
和""
表示字符串内容,单引号会原样输出,双引号会识别转义字符
1.2 数据类型
1.2.1 字面量
- date
- boolean
- string
- number
- null
1.2.2 对象
# 行内写法
k: {k1: v1, k2: v2, k3: v3}
# 或者
k:
k1: v1
k2: v2
k3: v3
1.2.3 数组
# 行内写法
k: [v1, v2, v3]
# 或者
k:
- v1
- v2
- v3
1.2.4 示例
创建 Person
类和 Pet
类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "person")
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> salaries;
private Map<String, List<Pet>> allPets;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Pet {
private String name;
private Double weight;
}
在 Yaml 中添加:
person:
userName: 张三
boss: false
birth: 2022/09/07 23:15:33
age: 18
pet:
name: tomcat
weight: 23.4
interests: [唱, 跳, Rap, 篮球]
animal:
- jerry
- mario
score:
english:
first: 30
second: 40
third: 50
math: [131, 140, 148]
chinese: {first: 128, second: 136}
salaries: [3999, 4999.98, 5999.99]
allPets:
sick:
- {name: 阿猫}
- {name: 杰瑞, weight: 47}
health: [{name: mario, weight: 47}]
在 HelloController
中添加:
@Autowired
Person person;
@RequestMapping("/person")
public Person person(){
return person;
}
访问 http://localhost:8080/person
:
2. 配置提示
默认情况下,Idea 不给 yaml 文件提示自定义类。
根据 官网文档,引入依赖:
<!-- yaml 提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
项目重启一下,然后就有提示了:
打包的时候避免将上述依赖一起打包(2.7.3 版本不用做该操作了,已经默认不导入了):
<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>