spring - 在 Spring Boot 中从多个 YAML 文件中读取值
问题描述
spring.config.location
可以接受托管 Spring Boot 应用程序的 yaml 文件的目录列表。
但是列出的目录必须有名为的文件applicaion.yml
,否则它们不会被拾取。
如果我的应用程序允许用户放置任何名称的 yaml 文件,那么我不能使用此选项。
然后我手动将文件名添加到属性中,如下所示
spring.config.location=/location1/file1.yml,/location2/file2.yml
每次添加新文件时,我都必须修改此属性。
我可以YamlPropertySourceLoader
用来读取所有文件并将所有属性放入 aMap
中,但是还有另一种更优雅的方法可以让我将这些值直接绑定到@Value
注释中。
使用我当前使用的代码片段进行更新,但正在寻找任何其他更好的选择。
Resource[] resources = applicationContext.getResources("classpath*:*.properties");
Map<Object, Object> map = new HashMap<>();
Arrays.stream(resources).forEach(res -> {
try {
propertiesPropertySourceLoader.load("resources", res)
.forEach(prop -> map.putAll((Map<?, ?>) prop.getSource()));
} catch (IOException e) {
e.printStackTrace();
}
});
解决方案
如果您的应用程序中有多个 yml/properties 文件,那么您可以@PropertySource("classpath:file.properties")
在配置类上使用,因此您将能够从该配置文件中读取值。
推荐阅读
- rust - tokio::run_async 与 tokio::net::UnixStream 恐慌
- python - 如何修复最后一个测试变量的错误返回语句?
- java - 当我添加 getActivity() 以从 Fragment 中的 firestore 检索数据时崩溃
- python - 单击按钮后如何自动刷新页面?
- javascript - 如何设置从另一个日期字段派生的一个日期字段的最小属性
- java - 来自子布局的 recyclerView 引用,包括
在父布局中 - c++ - 未定义的行为(程序突然停止)。我究竟做错了什么?
- javascript - 过滤大于或等于某个数字的数字(省略该数字)然后删除它们?
- c# - 将许可证数据添加到 winforms 应用程序
- python - ImportError: cannot import name 'BeautifulSoup' , bs4 已安装