加载多个YAML文件(使用@ConfigurationProperties吗?)

Ale*_*lex 5 java spring snakeyaml spring-boot

使用Spring Boot 1.3.0.RELEASE

我有几个yaml文件,它们描述了程序的多个实例。现在,我想将所有这些文件解析为一个List<Program>(映射,等等),以便以后可以在所有程序中针对给定条件搜索最合适的实例。

我非常喜欢这种方法@ConfigurationProperties,并且对于单个yaml文件来说效果很好,但是我还没有找到一种使用该方法读取目录中所有文件的方法。

适用于单个文件的当前方法:

programs/program1.yml

name: Program 1
minDays: 4
maxDays: 6
Run Code Online (Sandbox Code Playgroud)

可以被读取

@Configuration
@ConfigurationProperties(locations = "classpath:programs/program1.yml", ignoreUnknownFields = false)
public class ProgramProperties {

private Program test; //Program is a POJO with all the fields in the yml.
//getters+setters
Run Code Online (Sandbox Code Playgroud)

我尝试将位置更改为列出所有文件的数组locations = {"classpath:programs/program1.yml", "classpath:programs/program2.yml"},并使用locations = "classpath:programs/*.yml",但仍然仅加载第一个文件(数组方法)或根本不加载(通配符方法)。

所以,我的问题是,在Spring Boot中将一堆yaml文件加载到类路径目录中并将它们解析为POJO(列表),以便可以在Controller中自动进行连接的最佳方法是什么?我是否需要直接使用Snakeyaml,还是有一个我尚未发现的集成机制?

编辑:一种可行的方法是手动进行:

    private static final Yaml yaml = new Yaml(new Constructor(Program.class));
private static final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

try {
        for (Resource resource : resolver.getResources("/programs/*.yml")) {

            Object data = yaml.load(resource.getInputStream());

            programList.add((Program) data);
        }
    }
    catch (IOException ioe) {
        logger.error("failed to load resource", ioe);
    }
Run Code Online (Sandbox Code Playgroud)

小智 3

在 Spring 中,可以使用PropertySource注释加载多个配置属性文件,但不能加载 YAML 文件。请参阅以下链接中的第 26.6.4 节:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

但是,从您的问题来看,您似乎可以在单个 YAML 中配置所有程序,然后在单个列表中获取所有程序列表。

示例 YAML (all.yaml)

programs:
  - name: A
    min: 1
    max: 2
  - name: B
    min: 3
    max: 4
Run Code Online (Sandbox Code Playgroud)

配置文件

@Configuration
@ConfigurationProperties(locations={"classpath:all.yaml"})
public class Config{

    private List<Program> programs;

    public void setPrograms(List<Program> programs) {
        this.programs = programs;
    }

    public List<Program> getPrograms() {
        return programs;
    }
}
Run Code Online (Sandbox Code Playgroud)