1

I want to read this configuration YAML from Spring Boot:

host:
  api1: http://api1.com
  api2: http://api2.com
  api3: http://api3.com

into a Map and let it create a new Object so that it looks like this:

def apiUrls = ["api1":new Api("http://api1.com"),
                   "api2":new Api("http://api2.com"),
                   "api3":new Api("http://api3.com")]

I've already tried several solutions from Stack Overflow (e.g. this), but the result was always an empty map. The variables are definitely loaded (they are present in /management/env).

Does anyone know how to do it in Groovy?

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • you can use snakeyaml. example here: https://stackoverflow.com/questions/44881499/snakeyaml-appears-to-unnecessarily-wrap-simple-values-in-lists/44882014#44882014 – daggett Jul 11 '17 at 16:57

1 Answers1

0

It's perhaps a bit fuzzy in the docs, but for the maps you must:

  • always provide a getter;
  • either initialize the map or provide a setter.

When using Groovy, this will suffice:

@Component
@ConfigurationProperties(prefix = "props")
class Props {
    Map<String, String> vals
}

It will compile roughly into

public class Props implements GroovyObject {
    private Map<String, String> vals;

    public Map<String, String> getVals() { return this.vals; }
    public void setVals(Map<String, String> vals) { this.vals = vals; }
}


If it is crucial that only a getter method is present, the class can be written as follows:

@Component
@ConfigurationProperties(prefix = "props")
class Props {
    private Map<String, String> vals = [:]
    Map<String, String> getVals() { vals }
}

which will compile into something like this:

public class Props implements GroovyObject {
    private Map<String, String> vals;

    public Props() { /* Groovy magic including field initialization */ }

    public Map<String, String> getVals() { return this.vals; }
}
jihor
  • 2,478
  • 14
  • 28