Loading multiple YAML files (using @ConfigurationProperties?)

时间:2015-12-03 10:37:01

标签: java spring spring-boot snakeyaml

Using Spring Boot 1.3.0.RELEASE

I have a couple of yaml files that describe several instances of a program. I now want to parse all those files into a List<Program> (Map, whatever), so I can later on search for the most appropriate instance for a given criteria in all the programs.

I like the approach with @ConfigurationProperties a lot, and it works good enough for a single yaml-file, but I haven't found a way yet to read all files in a directory using that method.

Current approach working for a single file:

programs/program1.yml

name: Program 1
minDays: 4
maxDays: 6

can be read by

@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

I tried changing the locations to an Array listing all of my files locations = {"classpath:programs/program1.yml", "classpath:programs/program2.yml"} as well as using locations = "classpath:programs/*.yml", but that still only loads the first file (array-approach) or nothing at all (wildcard-approach).

So, my question is, what is the best way in Spring Boot to load a bunch of yaml files in a classpath-directory and parse them into a (List of) POJO, so they can be autowired in a Controller? Do I need to use Snakeyaml directly, or is there an integrated mechanism that I just haven't found yet?

EDIT: A working approach is doing it manually:

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

2 个答案:

答案 0 :(得分:4)

就我理解你的问题而言,我目前正在做的事情几乎是一样的。 我有一个application.yml以及特定于配置文件的yml文件,例如我application-{profile}.yml中的src/main/resources。 在application.yml我已经定义了默认的配置文件键值,它们被特定于配置文件的yml文件部分覆盖。

如果您希望对YML键/值进行类型安全且定义良好的访问,则可以使用以下方法:

 @ConfigurationProperties
 public class AppSettings {
     String name; // has to be the same as the key in your yml file

     // setters/getters

 }

在Spring-Boot配置中,您必须在配置类中添加以下注释:

@ComponentScan
@EnableAutoConfiguration
@EnableConfigurationProperties( value = { AppSettings.class, SomeOtherSettings.class } )
public class SpringContextConfig {

     @Autowired
     private AppSettings appSettings;

     public void test() {
          System.out.println(appSettings.getName());
     }
}

也可以从其他Bean访问@Autowiring。 反过来(没有额外的分隔和类型安全的类,是通过@Value("${name}")访问YML值。

以简短的方式将它们组合在一起: 是的,可以通过Spring-profiles为您的应用程序使用多个YAML文件。您可以通过命令args,以编程方式或通过系统env(SPRING_PROFILES_ACTIVE = name1,name2)定义当前的活动弹簧配置文件。 因此,每个配置文件可以有多个application.yml个文件(参见上文)。

答案 1 :(得分: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

Config.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;
    }
}