Rinkashikachi
Rinkashikachi

Reputation: 134

Spring @Value annotation with List and default value

I have a property in config file, which contains a list of values in such format. The format has to remain the same. myapp.values=value1,value2,value2

I use these values in my config class like that:

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

My question is there a way to make a default value (empty list or null) it there is no such property in config file or the property is empty?

I tried to google this with no success. People either use myapp.values={value1,value2,value3} which doesn't suit me or format for that or use default values for simple variables, not lists.

My question is only about achieving the goal by changing the @Value annotation. Pls do not suggest workarounds

Upvotes: 1

Views: 4535

Answers (2)

Desmond Stonie
Desmond Stonie

Reputation: 137

Actually, just one symbol : with an empty default value will work:

@Value("${myapp.values:}")
private List<String> values;

Upvotes: 4

jcompetence
jcompetence

Reputation: 8383

@Value("${myapp.values:}#{T(java.util.Collections).emptyList()}")
private List<String> defaultToEmpty;

or

@Value("#{T(java.util.Arrays).asList('${myapp.values:}')}")
private List<String> defaultToEmpty = new ArrayList();

Upvotes: 5

Related Questions