首页 > 解决方案 > 在 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();
            }
        });

标签: springspring-bootyaml

解决方案


如果您的应用程序中有多个 yml/properties 文件,那么您可以@PropertySource("classpath:file.properties")在配置类上使用,因此您将能够从该配置文件中读取值。

欲了解更多信息查看


推荐阅读