Question
How can I correctly retrieve multiple values from a Spring .properties file and store them as an array or list?
base.module.elementToSearch=1,2,3,4,5,6
Answer
When using Spring to load properties from a .properties file, multiple entries with the same key will not aggregate values into a list automatically. Instead, only the last value is retained. To solve this and effectively retrieve multiple values as a list, you can utilize a combination of property handling and the SpEL (Spring Expression Language).
<bean id="some"
class="com.some.Class">
<property name="property" value="#{{'${base.module.elementToSearch}'.split(',')}}" />
</bean
Causes
- Spring's property resolver does not support mapping multiple properties with the same key directly into a collection.
- The last defined property overwrites previous entries when using the same key.
Solutions
- Aggregate the values in a single property entry, like you mentioned (using commas to separate values).
- Alternatively, you can create a custom property editor or use Spring's conversion service for more complex scenarios.
Common Mistakes
Mistake: Defining multiple properties with the same key in the .properties file and expecting them to aggregate automatically.
Solution: Use a single property with values separated by commas instead.
Mistake: Assuming that just using SpEL will work without correct formatting of the property value in the XML configuration.
Solution: Ensure your property value is formatted correctly to utilize SpEL effectively.
Helpers
- Spring properties file
- load properties as array Spring
- Spring list from properties
- Spring multiple properties key
- properties file array configuration