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.
I think this is simpler for grabbing the array and stripping spaces:
Since Spring 3.0, you can add a line like
to your
applicationContext.xml
(or where you configure things). As Dmitry Chornyi points out in a comment, Java based configuration looks like:This activates the new configuration service which supports converting
String
toCollection
types. If you do not activate this configuration service, Spring falls back on its legacy property editors as configuration services, which do not support this kind of conversion.Converting to collections of other types works, too:
will work with a line like
No problems with whitespace there, the
ConversionServiceFactoryBean
takes care of it.See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert-Spring-config
you can do this with annotations like this
here my.list.of.strings will be picked from the properties file, if its not there, then the defaults a,b,c will be used
and in your properties file, you can have something like this
my.list.of.strings=d,e,f
Using Spring EL:
Assuming your properties file is loaded correctly with the following:
Have you considered
@Autowired
ing the constructor or a setter andString.split()
ing in the body?I tend to prefer doing my autowiring in one of these ways to enhance the testability of my code.
Beware of spaces in the values. I could be wrong, but I think spaces in the comma-separated list are not truncated using @Value and Spel. The list
would be read in as a list of strings
In most cases you would probably not want the spaces!
The expression
would give you a list of strings:
The regular expression removes all spaces just before and just after a comma. Spaces inside of the values are not removed. So
should result in values