James Baker James Baker - 16 days ago 13
YAML Question

Getting lists from Spring Boot configuration

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.

Answer

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