Map Yaml to Object Hashmap in Springboot

Spring Boot - inject map from application.yml

You can have a map injected using @ConfigurationProperties:

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class MapBindingSample {

public static void main(String[] args) throws Exception {
System.out.println(SpringApplication.run(MapBindingSample.class, args)
.getBean(Test.class).getInfo());
}

@Bean
@ConfigurationProperties
public Test test() {
return new Test();
}

public static class Test {

private Map<String, Object> info = new HashMap<String, Object>();

public Map<String, Object> getInfo() {
return this.info;
}
}
}

Running this with the yaml in the question produces:

{build={artifact=${project.artifactId}, version=${project.version}, name=${project.name}, description=${project.description}}}

There are various options for setting a prefix, controlling how missing properties are handled, etc. See the javadoc for more information.

Spring Boot - Injecting a map from a YAML file

We have something similar in our code. This is how we solved it.

application.yml

validation:
synonyms:
Doctor: Dr.
Sanct: St.

Config

@Component
@ConfigurationProperties("validation")
public class ValidationConfig {

private Map<String, String> synonyms;
// ...
}

You can find more information for this topic in the documentation: Spring Boot Externalized Configuration

Spring Boot yaml nested property map to Configuration class HashMap

This example does indeed work fine. My particular problem was a config file that wasn't being read.

How to bind a yml map to a Java map in spring-boot configuration?

Your yml structure isn't correct. Change your yml like this

symbols:
symbolPairs.[CombinationsAlpha]: aaabbb, bbbaaa, ccceee, dddggg
symbolPairs.[CombinationsInteger]: 000111, 222666, 999000, 151515

Here is the output

enter image description here



Related Topics



Leave a reply



Submit