前言
SpringBoot项目读取Yaml配置中的数据
创建为了测试用的配置文件
src/main/resources/application.yml1 2 3 4 5
| father: son1: value son2: - value1 - value2
|
直接获取Yaml中的字符串数据
1 2
| @Value("${father.son1}") private String value;
|
直接获取Yaml中数组的某个数据
1 2
| @Value("${father.son2[0]}") private String value;
|
通过环境对象获取所有数据
获取所有配置文件
1 2
| @Autowired private Environment environment;
|
获取指定配置文件
1 2 3
| environment.getProperty("father.son1")
environment.getProperty("father.son2[0]")
|
通过实体类获取所有数据
创建实体类
@ConfigurationProperties(prefix = "")
:指定配置文件根级配置的键名
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 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.controller.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component @ConfigurationProperties(prefix = "father") public class Father {
private String son1; private String[] son2;
public String getSon1() { return son1; }
public void setSon1(String son1) { this.son1 = son1; }
public String[] getSon2() { return son2; }
public void setSon2(String[] son2) { this.son2 = son2; }
@Override public String toString() { return "Father{" + "son1='" + son1 + '\'' + ", son2=" + Arrays.toString(son2) + '}'; } }
|
踩坑
- IDEA提示:
Spring Boot Configuration Annotation Processor not configured
,这个提示不能隐藏
解决问题
- 添加依赖
spring-boot-configuration-processor
pom.xml1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
|
完成
- 完成后提示:
Re-run Spring Boot Configuration Annotation Processor to update generated metadata
,这个提示可以隐藏
获取包含所有配置的对象
1 2
| @Autowired private Father father;
|
完成
参考文献
哔哩哔哩——黑马程序员 CSDN——lllllLiangjia