2

My Spring Boot application doesn't seem to be recognising lists in my configuration file (application.yml). Below is roughly what I'm trying to do.

Java Code:

@Autowired
private Environment environment;

public class Config{
  public Config(){
  }

  public List<String> getDateFields(){
    return environment.getProperty("dates.fields", List.class);
  }
}

application.yml:

dates:
  fields:
  - date
  - creationDate

getDateFields returns null above. However, if I use the following...

application.yml:

dates:
  fields: creationDate

...it works fine and returns it as a list (albeit a single valued one). Why can't I get the list from my application.yml file? I tried checking whether environment even contained dates.fields, and environment.containsProperty("dates.fields") returns false when using the list version.

1 Answer 1

6

Use coma separated format, for your list properties if you want to load the values as List using environment.getProperty("dates.fields", List.class);

dates:
  fields: date, creationDate

that way goes well for me.

However if you want to use

dates:
  fields:
     - date
     - creationDate

Then better use the following aproach to load the properties from yaml file.

@Component
@ConfigurationProperties(prefix = "dates")
public class Config{

   private List<String> fields = new ArrayList<String>();

   public List<String> getDateFields(){
      return this.fields;
   }
}
Sign up to request clarification or add additional context in comments.

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.