小编Ale*_*lex的帖子

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

使用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 …
Run Code Online (Sandbox Code Playgroud)

java spring snakeyaml spring-boot

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×1

snakeyaml ×1

spring ×1

spring-boot ×1