How to fill HashMap from java property file with Spring @Value

d-sauer picture d-sauer · Feb 6, 2015 · Viewed 93.9k times · Source

Is it possible to use Spring @Value, to map values from properties file to the HashMap.

Currently I have something like this, and mapping one value is not a problem. But I need to map custom values in HashMap expirations. Is something like this possible?

@Service
@PropertySource(value = "classpath:my_service.properties")
public class SomeServiceImpl implements SomeService {


    @Value("#{conf['service.cache']}")
    private final boolean useCache = false;

    @Value("#{conf['service.expiration.[<custom name>]']}")
    private final HashMap<String, String> expirations = new HashMap<String, String>();

Property file: 'my_service.properties'

service.cache=true
service.expiration.name1=100
service.expiration.name2=20

Is it posible to map like this key:value set

  • name1 = 100

  • name2 = 20

Answer

Marc Bouvier picture Marc Bouvier · Sep 21, 2018

You can use the SPEL json-like syntax to write a simple map or a map of list in property file.

simple.map={'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}

map.of.list={\
  'KEY1': {'value1','value2'}, \
  'KEY2': {'value3','value4'}, \
  'KEY3': {'value5'} \
 }

I used \ for multiline property to enhance readability

Then, in Java, you can access and parse it automatically with @Value like this.

@Value("#{${simple.map}}")
Map<String, String> simpleMap;

@Value("#{${map.of.list}}")
Map<String, List<String>> mapOfList;

Here with ${simple.map}, @Value gets the following String from the property file:

"{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}"

Then, it is evaluated as if it was inlined

@Value("#{{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}}")

You can learn more in the official documentation