Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot read properties without prefix to a map

I need to read all properties in application.properties file in a map In the code below the property test has the respective value but the map is empty. How can I fill "map" with the values in the application.properties file without adding a prefix to the properties.

This is my application.properties file

AAPL=25
GDDY=65
test=22

I'm using @ConfigurationProperties like this

@Configuration
@ConfigurationProperties("")
@PropertySource("classpath:application.properties")
public class InitialConfiguration {
    private HashMap<String, BigInteger> map = new HashMap<>();
    private String test;

    public HashMap<String, BigInteger> getMap() {
        return map;
    }

    public void setMap(HashMap<String, BigInteger> map) {
        this.map = map;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
like image 316
Jorge Miralles Avatar asked Sep 10 '18 04:09

Jorge Miralles


1 Answers

This can be achieved using the PropertiesLoaderUtils and @PostConstruct

Please check the sample below:

@Configuration
public class HelloConfiguration {
    private Map<String, String> valueMap = new HashMap<>();
    @PostConstruct
    public void doInit() throws IOException {
        Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
        properties.keySet().forEach(key -> {
            valueMap.put((String) key, properties.getProperty((String) key));
        });
        System.err.println("valueMap -> "+valueMap);
    }
    public Map<String, String> getValueMap() {
        return valueMap;
    }
    public void setValueMap(Map<String, String> valueMap) {
        this.valueMap = valueMap;
    }
}
like image 84
Saikat Avatar answered Sep 27 '22 22:09

Saikat