Similar to this question: http://forum.springsource.org/showthread.php?111992-Loading-a-list-from-properties-file-using-Value-annotation (for which there's no reply on)
I want to have a list of values in a .properties file, ie:
my.list.of.strings=ABC,CDE,EFG
And to load it in my class directly, ie:
@Value("${my.list.of.strings}")
private List<String> myList;
As I understand, an alternative of doing this is to have it in the spring config file, and load it as a bean reference (correct me if I'm wrong), ie
<bean name="list">
<list>
<value>ABC</value>
<value>CDE</value>
<value>EFG</value>
</list>
</bean>
But is there any way of doing this? using a .properties file? ps: I would like to do this with out any custom code if possible.
Consider using Commons Configuration. It have built in feature to break an entry in properties file to array/list. Combing with SpEL and @Value should give what you want
As requested, here is what you need (Haven't really tried the code, may got some typoes, please bear with me):
In Apache Commons Configuration, there is PropertiesConfiguration. It supports the feature of converting delimited string to array/list.
For example, if you have a properties file
With the below code:
will give you a string array of
["bar1", "bar2", "bar3"]
To use with Spring, have this in your app context xml:
and have this in your spring bean:
I believe this should work :P
If you are using latest Spring framework version(Spring 3.1+ I believe), you don't need to those string split stuff in SpringEL,
Simply add PropertySourcesPlaceholderConfigurer and DefaultConversionService in your Spring's Configuration class ( the one with annotated with Configuration ) e.g,
and in your class
and in the properties file
Without DefaultConversionService, you can only take comma separated String into String array when you inject the value into your field, but DefaultConversionService does a few convenient magic for you and will add those into Collection, Array, etc. ( check the implementation if you'd like to know more about it )
With these two, it even handles all the redundant whitespaces including newline, so you don't need to add additional logics to trim them.
If you are reading this and you are using Spring Boot, you have 1 more option for this feature
Usually comma separated list are very clumsy for real world use case (And sometime not even feasible, if you want to use commas in your config):
With Spring Boot, you can write it like these (Index start at 0):
And use it like these:
If you are using Spring Boot 2, it works as is, without any additional configuration.
if using property placeholders then ser1702544 example would become
With placeholder xml:
By specifying the the
my.list.of.strings=ABC,CDE,EFG
in .properties file and using@Value("${my.list.of.strings}")
private String[] myString;
You can get the arrays of strings. And using
CollectionUtils.addAll(myList, myString)
, you can get the list of strings.