Abdullah
Abdullah

Reputation: 401

Reading a Map from properties file and load with spring annotation @Value

I have a list of (key/value) need to be populated to a map on a spring bean:

dmin.details.fieldsMap=name,Abdullah,\
             street,Zayed,\
             phone,+201020102010

It's working fine with me using a list as below:

property:

dmin.details.fields=Abdullah,Zayed,+201020102010

Calling:

@Value("#{'${dmin.details.fields}'.split(',')}")
private List<String> fields;

Could anyone advise if this is doable in Spring?

Upvotes: 3

Views: 19694

Answers (3)

Hari Rao
Hari Rao

Reputation: 3240

I found a slightly different case and explaining that below, in case if somebody is looking for it.

  1. I had trade_id_date={'123WC':'20100125', '234W':'20100125', 1689332:'20100125'} in properties file
  2. Below in a java class

    @Value("#{${trade_id_date}}") private Map tradeIdDateMap;

If you do not enclose the left hand side in single quotes if it is alphanumeric then you will get

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException
@0: EL1044E: Unexpectedly ran out of input
  1. So make sure you enclose that in single quotes

Upvotes: 0

Vladimir Prudnikov
Vladimir Prudnikov

Reputation: 176

application.properties:

property.map={first:value, second:value}

then in Java code you can:

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

Upvotes: 16

Abdullah
Abdullah

Reputation: 401

As I didn't find any way in spring to read the property as a Map, I had to fill the map myself using the list filled by spring as below :

@Value("#{'${dmin.details.fields}'.split(',')}")
private List<String> fields;

private Map<String, String> fieldsMap;

@PostConstruct
public void init() {
    fieldsMap = new HashMap<String, String>();
    if (fields != null && fields.size() != 0) {
        for (String field : fields) {
            String[] splittedField = field.split(",");
            fieldsMap.put(splittedField[0], splittedField[1]);
        }
    }
}

Upvotes: 1

Related Questions