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;
}
}
CodePudding user response:
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.