注意:此种方式在修改yml文件之后就会立即读取到新的值,不需要重启服务,但不重启会导致后台和前台拿到的数据不一致,谨慎使用
引入snakeyaml
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
application.yml
spring:
profiles:
#环境
active: dev
application-dev.yml
#微信公众号 (测试号)
wechat:
appId: wxh123242hh3h25
读取yaml工具类
package com.ainsg.apps.aop.common.utils;
import org.apache.ibatis.io.Resources;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
/**
* 读取 yml 工具类
*
* @author: ChenRuiYao
* @since: 2020-07-30 09:35
* @Version: 1.0
*/
public class YamlUtil {
/**
* 读取 ymal
*
* @param path 需要读取的文件路径
* @return Map
*/
public static Map getReadAbleYaml(String path) {
Yaml yaml = new Yaml();
Map obj = null;
InputStream ins = null;
try {
ins = Resources.getResourceAsStream(path);
obj = (Map) yaml.load(ins);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ins != null) {
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
}
应用
package com.ainsg.apps.aop.modules.sys.controller;
import com.ainsg.apps.aop.common.utils.YamlUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/yaml")
public class YamlController {
/**
* 获取对应环境中的 appid (wechat.appId)
*
* @author: ChenRuiYao
* @since: 2020/7/30 16:04
*/
@GetMapping("/getAppId")
@ResponseBody
public String getAppId() {
String active = getEnv();
Map env = YamlUtil.getReadAbleYaml("application-" + active + ".yml");
Map wechat = (Map) env.get("wechat");
String appId = wechat.get("appId").toString();
return appId;
}
/**
* 获取 application.yml 中的环境信息 (spring.profiles.active)
*
* @author: ChenRuiYao
* @since: 2020/7/30 16:04
*/
@GetMapping("/getEnv")
@ResponseBody
public String getEnv() {
Map properties = YamlUtil.getReadAbleYaml("application.yml");
Map spring = (Map) properties.get("spring");
Map profiles = (Map) spring.get("profiles");
String active = profiles.get("active").toString();
return active;
}
}