2

I've a properties file in which the values are comma separated. I'm able to get the values as Object as below. Could anyone please tell me how to separate the values and get it in String.

.properties

key-1 = value1,value11
key-2 = value2,value22
key-3 = value3,value33
key-4 = value4,value44

Code

@PropertySource( value = "classpath:test1.properties", name = "test1" )

AbstractEnvironment ae = (AbstractEnvironment)env;
org.springframework.core.env.PropertySource test1Source = 
ae.getPropertySources().get("test1");
Properties propsTest1 = (Properties)test1Source.getSource();

   for(Object key : propsTest1.keySet()){
   System.out.println("Properties file======>   propsTest1.get(key));
  }
Sam
  • 513
  • 1
  • 11
  • 27
  • Spring Expression Language ([SPEL](https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html)) will help your case. Check this question for some insight: https://stackoverflow.com/questions/12576156/reading-a-list-from-properties-file-and-load-with-spring-annotation-value – vahdet Mar 15 '19 at 09:40
  • please share your expected output as well. – Vinay Prajapati Mar 15 '19 at 10:34

3 Answers3

3

You can use @Value annotation with @PropertySource to get the value of a property. Also, you can use Spring Expression to split it into list, e.g.:

@PropertySource( value = "classpath:test1.properties", name = "test1" )
public class PropertyClass {

    @Value("#{'${key-1}'.split(',')}") 
    private List<String> key1Values;
}

This would give you the list of all the values configured against key-1.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Is there a way to get the values dynamically than creating a variable for every key? – Sam Mar 15 '19 at 09:42
  • 1
    Don't think there is any way to do this unless you subclass `PropertyPlaceholderConfigurer`, read here : https://stackoverflow.com/a/11416312/1120793 – Darshan Mehta Mar 15 '19 at 09:43
  • This answer is good. But, I accepted Vinay's answer because it solved my problem. Upvoted your answer too. Thanks – Sam Mar 15 '19 at 10:33
2

You can try something like below.

Properties propsTest1 = (Properties)test1Source.getSource();

for(Map.Entry<Object, Object> e : propsTest1.entrySet()){

   String value = (String)e.getValue();
   String[] values = value.split(",");
   // If you have spaces as between values, you have to take care of it.
}
vavasthi
  • 922
  • 5
  • 14
2

.properties

map.key[0] = value1,value11
map.key[1] = value2,value22
map.key[2] = value3,value33
map.key[3] = value4,value44

Code

@ConfigurationProperties(prefix="map")
public class YourConfig {

    private List<String> keys = new ArrayList<String>();

    public List<String> getKeys() {
        return this.servers;
    }
}

Or you can use:

keys={key-1:'value1',key-1:'value2',....}

Code

@Value("#{${keys}}")  private Map<String,String> keys;
Ihor Horovyi
  • 143
  • 4