使用 Spring Boot 1.3.0.RELEASE
我有几个 yaml 文件,它们描述了程序的多个实例。我现在想将所有这些文件解析为List<Program>
(地图,等等),这样我以后就可以在所有程序中搜索给定条件的最合适的实例。
我喜欢这种方法@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(列表)的最佳方法是什么,以便它们可以在控制器中自动装配?我需要直接使用 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);
}