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)); } 
2
  • Spring Expression Language (SPEL) will help your case. Check this question for some insight: stackoverflow.com/questions/12576156/… Commented Mar 15, 2019 at 9:40
  • please share your expected output as well. Commented Mar 15, 2019 at 10:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to get the values dynamically than creating a variable for every key?
Don't think there is any way to do this unless you subclass PropertyPlaceholderConfigurer, read here : stackoverflow.com/a/11416312/1120793
This answer is good. But, I accepted Vinay's answer because it solved my problem. Upvoted your answer too. Thanks
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. } 

2 Comments

I like @Darshan Mehta's answer better.
Thanks. This helped.
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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.