5

I have a configuration class named CommonConfig that has been working fine so far…

@Data
@Component
@ConfigurationProperties(prefix = “my")
public class CommonConfig {
  private String foo;
  private String bar;
  private SubA subA;

  @Data 
  public static class SubA {
    private String baz;
    private SubB subB;

    @Data 
    public static class SubB {
      private String qux;
    }
  }
}

And the Yaml property file to go with that:

my.foo: a
my.bar: b
my.sub-a.baz: c
my.sub-a.sub-b.qux: d

My problem started when I wanted to get a map into SubB:

my:
  foo: a
  bar: b
  sub-a:
    baz: c
    sub-b:
      qux: d
      map:
        number-one: 1
        number-two: 2
        number-three: 3

I tried adding a simple map declaration inside my SubB class:

...
@Data 
public static class SubB {
  private String qux;
  private Map<String, Integer> map = new HashMap<>();
}

When I run this though, all the other properties are in the config, but the map is empty. I also tried not initializing the map, but it stays null.

My @SpringBootApplication class has previously been working fine with just that one annotation on it. Based on some other StackOverflow questions, I tried adding @EnableConfigurationProperties, but it made no difference.

2
  • 1
    Works for me. If you post a link to a complete project we might be able to see what you did that you aren't telling us. Commented Jan 4, 2017 at 7:28
  • Thank you very much for checking! I made the sample as described and it worked for me as well so I started porting over my actual app to see what was different. It all boiled down to not reading a property file because the application name didn't match. Chalk another one up to PEBKAC or ID-10-T error. :/ Commented Jan 4, 2017 at 12:16

2 Answers 2

2

This example does indeed work fine. My particular problem was a config file that wasn't being read.

Sign up to request clarification or add additional context in comments.

Comments

1
  1. In case of YAML files, application.ymlgets loaded automatically. If the file name is something else, Spring won't auto-load that.
  2. @PropertySource as of SprintBoot 2.1 doesn't work for YAML
  3. in case the YAML file needs a different name, we need to set spring.config.name and spring.config.location
    https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-yaml
  4. Following link also points to a good answer:
    Reading a map from yaml in Java getting null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.