栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 使用官方工具类手动读取yml文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 使用官方工具类手动读取yml文件

代码: 

    //读取文件
	private Map getResource(String classPath) {
		ClassPathResource resource = new ClassPathResource(classPath);
		InputStream inputStream;
		Yaml yaml = new Yaml();
		Map res = new linkedHashMap<>();
		try {
			inputStream = resource.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			Map map = yaml.load(reader);
			buildFlattenedMap(res, asMap(map), null);
		} catch (IOException e) {
			LOGGER.info("get input stream fail", e);
		}
		return res;
	}

    //转为map
	private Map asMap(Object object) {
		// YAML can have numbers as keys
		Map result = new linkedHashMap<>();
		if (!(object instanceof Map)) {
			// A document can be a text literal
			result.put("document", object);
			return result;
		}

		Map map = (Map) object;
		map.forEach((key, value) -> {
			if (value instanceof Map) {
				value = asMap(value);
			}
			if (key instanceof CharSequence) {
				result.put(key.toString(), value);
			} else {
				// It has to be a map key in this case
				result.put("[" + key.toString() + "]", value);
			}
		});
		return result;
	}

    
	private void buildFlattenedMap(Map result, Map source, @Nullable String path) {
		source.forEach((key, value) -> {
			if (org.springframework.util.StringUtils.hasText(path)) {
				if (key.startsWith("[")) {
					key = path + key;
				} else {
					key = path + '.' + key;
				}
			}
			if (value instanceof String) {
				result.put(key, value);
			} else if (value instanceof Map) {
				// Need a compound key
				@SuppressWarnings("unchecked")
				Map map = (Map) value;
				buildFlattenedMap(result, map, key);
			} else if (value instanceof Collection) {
				// Need a compound key
				@SuppressWarnings("unchecked")
				Collection collection = (Collection) value;
				if (collection.isEmpty()) {
					result.put(key, "");
				} else {
					int count = 0;
					for (Object object : collection) {
						buildFlattenedMap(result, Collections.singletonMap(
							"[" + (count++) + "]", object), key);
					}
				}
			} else {
				result.put(key, (value != null ? value : ""));
			}
		});
	} 

测试:

	public static void main(String[] args) {
		Map res = new TestClass().getResource("application-dev1.yml");
		System.out.println(res);
	}

结果:

{spring.application.name=test, server.port=80}

结果为key value形式

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号