简体   繁体   中英

How to bind Map<String,Object> to @ConfigurationProperties at top level?

Example YAML

apps:
  google:
    name: Google
    type: Search Engine
  bing:
    name: Bing
    type: Search Engine

Example Spring bean

@Getter
@Setter
@Component
@ConfigurationProperties("apps")
public class Apps extends HashMap<String, AppConfig> {

  @Getter
  @Setter
  static class AppConfig {
    private String name;
    private String type;
  }
}

That doesn't seem to work. Any way to bind map from YAML at top level?

The following will work but this requires an extra property at lower level in YAML file.

apps:
  config:
    google:
      name: Google
      type: Search Engine
    bing:
      name: Bing
      type: Search Engine
@Getter
@Setter
@Component
@ConfigurationProperties("apps")
public class Apps {

  private Map<String, AppConfig> config;

  @Getter
  @Setter
  static class AppConfig {
    private String name;
    private String type;
  }
}

The following should be enough for you

@Getter
@Setter
@Component
@ConfigurationProperties  // <--------
public class Apps {

  private Map<String, AppConfig> apps;  // <-------

  @Getter
  @Setter
  static class AppConfig {
    private String name;
    private String type;
  }
}

to map the example yaml of

apps:
  google:
    name: Google
    type: Search Engine
  bing:
    name: Bing
    type: Search Engine

By modyfying @ConfigurationProperties("apps") into @ConfigurationProperties you instruct that you want the parsing to start from top level of yaml which is apps . Your version with @ConfigurationProperties("apps") asks spring to start the mapping from first level children element after apps .

By naming the java class field to apps on the line private Map<String, AppConfig> apps; you instruct spring that it expects to find a yaml element named apps from where it starts reading, which according to the previous explanation will be the root of the yaml.

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