gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:49 25 4
gpt4 key购买 nike

使用 Spring Boot 1.3.0.RELEASE

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

我喜欢 @ConfigurationProperties 的方法很多,它对单个 yaml 文件来说已经足够好了,但我还没有找到一种方法来使用该方法读取目录中的所有文件。

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

programs/program1.yml

name: Program 1
minDays: 4
maxDays: 6

可以阅读

@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

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

所以,我的问题是,在 Spring Boot 中加载类路径目录中的一堆 yaml 文件并将它们解析为 POJO(列表)的最佳方法是什么,以便它们可以在 Controller 中 Autowiring ?我需要直接使用 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);
}

最佳答案

在 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

配置.java

@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;
}
}

关于java - 加载多个 YAML 文件(使用@ConfigurationProperties?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34063678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com