6

I am using PropertyPlaceholderConfigurer to map String values from properties file and it works ok.

My question is if I can set something the this in my property file: myList=A,B,C

And then map it to a list

@Value("${myList}")
private List<String> myList;

When I try that it puts all the values in one place of the list. Is there any way to tell it to break this to a list by ","?

Joly
  • 3,218
  • 14
  • 44
  • 70

2 Answers2

12

Using Spring Expression language:

 @Value("#{'${myList}'.split(',')}") 
 private List<String> myList;

If myList=A,B,C in property file this will result in myList (in the code) with the values A, B and C

Wilhelm Kleu
  • 10,821
  • 4
  • 36
  • 48
  • Note that the original code would work without the .split(), if you're using spring 3 and you define a conversion service - http://stackoverflow.com/a/29970335/228369 – chrismarx Jan 20 '16 at 16:10
0

Take a look at sections 6.5.3 (Inline Lists) and 6.5.4 (Array Construction) on this link to Spring Expression Language Features.

From the link:

Lists can be expressed directly in an expression using {} notation.

// evaluates to a Java list containing the four numbers
List numbers = (List) parser.parseExpression("{1,2,3,4}").getValue(context); 

List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context);

{} by itself means an empty list. For performance reasons, if the list is itself entirely composed of fixed literals then a constant list is created to represent the expression, rather than building a new list on each evaluation.

I am not sure that this will work exactly like you would like it to with the @Value annotation in combination with the PropertyPlaceholderConfigurer, but it is worth a look.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120