Reputation: 6612
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()}")
Upvotes: 6
Views: 11783
Reputation: 12744
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.
Upvotes: 11
Reputation: 27
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.
Upvotes: -2
Reputation: 806
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.
Upvotes: 3
Reputation: 27058
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(","));
}
Upvotes: 3