简体   繁体   中英

Load YAML configuration into a Groovy Map

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 (eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM