SpringBoot中如何优雅的读取yml配置文件?

YAML是一种简洁的非标记语言,以数据为中心,使用空白、缩进、分行组织数据,从而使得表示更加简洁易读。本文介绍下YAML的语法和SpringBoot读取该类型配置文件的过程。

本文目录

一、YAML基本语法

  1. 以缩进代表层级关系
  2. 缩进不能使用tab,只能用空格
  3. 空格个数不重要,但是同一层级必须左对齐
  4. 大小写敏感
  5. 数据格式为,名称:(空格)值
  6. 注释单行用#,只能注释单行

二、YAML支持的数据格式

  1. 字面量:数字、字符串、布尔等不可再分的值

字符串默认不需要加单引号或者双引号,如果加双引号,它不会转义字符串里面的特殊字符,而加单引号,则会转义字符串里面的特殊字符,意思就是将特殊字符直接变为字符串输出。

SpringBoot中如何优雅的读取yml配置文件?

例子:

key1: 1
key2: true
  1. 对象:即为键值对,key= value

用冒号分隔键值对(Key: Value), Key需要顶格写,前面不能有空格,冒号后面需要有一个空格然后再跟值, 相同的缩进属于同一个map。

例子:

server:
port: 8888
servlet:
context-path: /
  1. 数组:一组按顺序排列的值

用-来表示数组中的一个元素。

例子:

wechat:
mp:
configs:
- appid: appid1
secret: arr1_secret
token: arr1_token
aesKey: arr1_key
msgDataFormat: JSON
- appid: appid2
secret: arr2_secret
token: arr2_token
aesKey: arr2_key
msgDataFormat: JSON

三、读取yml配置文件

新建一个spring boot项目spring-boot-encry,按照下面步骤操作。

  1. 新建配置文件

application.yml内容如下:

wechat:
mp:
configs:
- appid: appid1
secret: arr1_secret
token: arr1_token
aesKey: arr1_key
msgDataFormat: JSON
- appid: appid2
secret: arr2_secret
token: arr2_token
aesKey: arr2_key
msgDataFormat: JSON
server:
port: 8888
servlet:
context-path: /
  1. 添加配置文件对应的实体类

实体类添加注解,@ConfigurationProperties,@ConfigurationProperties注解可以自定义实体类,映射yml或者properties文件,自动为对象bean属性捆绑数据。

WxMpProperties代码如下:

@Data
@ConfigurationProperties(prefix = "wechat.mp")
public class WxMpProperties {
private List<MpConfig> configs;
@Data
public static class MpConfig {
/**
* 设置微信公众号的appid
*/
private String appId;
/**
* 设置微信公众号的app secret
*/
private String secret;
/**
* 设置微信公众号的token
*/
private String token;
/**
* 设置微信公众号的EncodingAESKey
*/
private String aesKey;
}
}
  1. 添加controller

添加读取yml文件的controller,打印yml配置信息,代码如下:

/**
* 读取yml文件的controller
*
* @Authro Java碎碎念
*/
@Slf4j
@RestController
public class TestReadYmlController {
@Value("${server.port}")
private Integer port;
@Autowired
private WxMpProperties wxMpProperties;
@RequestMapping("/readYml")
public void readYml() {
log.info("server.port=" + port);
log.info("wxMpProperties=" + JSON.toJSONString(wxMpProperties));
}
}

四、测试

打开浏览器访问:http://localhost:8888/readYml,可看到后台已经打印了yml配置文件里的信息,说明读取成功。

您可能还会对下面的文章感兴趣: