6

I am struggling in obtaining both of the behaviors requested in the title. 1) I have a property file like this:

my.list=a,b,c

2) If that property is not present I want an empty list

Why the following is throwing me syntax error?

@Value("#{'${my.list}'.split(',') : T(java.util.Collections).emptyList()}")
3
  • I am not sure, if you can do a nested SPEL Commented Mar 19, 2018 at 16:01
  • Confirmed: I get the "," inside of the first array element :( Commented Mar 19, 2018 at 16:05
  • try this: @Value("#{T(java.util.Arrays).asList('${my.list:}')}") Commented Mar 19, 2018 at 16:15

4 Answers 4

11

There is a way to get it working:

@Value("#{T(java.util.Arrays).asList('${my.list:}')}") 
private List<String> list;

After the colon at my.list: you can set the default value. For now its emtpy.

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

3 Comments

will it split also ?
yes it will split
yes it split, but where is the .split command in case I don't want ',' char
3

I don't think you can use nested SPEL. one way to achieve this is

@Value("${server.name:#{null}}")
private String someString;

private List<String> someList;

@PostConstruct
public void setList() {
  someList = someString == null ? Collections.emptyList() : Arrays.asList(someString.split(","));
}

Comments

3

Did came across similar requirement. Below is one of the possible way of doing this :

@Value("#{'${some.key:}'.split(',')}")
Set<String> someKeySet;

I think similar should apply for List as well.
Pay attention to ":" after property name. It defaults to blank string which in turn would give empty list or set.

1 Comment

It does not create an empty Set, it creates a Set with one empty string element [""].
-2

The best way to achieve this will be

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

If key is not present in application.properties, we are initialising with a empty list.

1 Comment

No, this creates a list with one empty string in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.