Phate
Phate

Reputation: 6612

Spring @Value with arraylist split and default empty list

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

Answers (4)

Patrick
Patrick

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

Amandeep Singh
Amandeep Singh

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

bittu
bittu

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

pvpkiran
pvpkiran

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

Related Questions