Reputation: 182
I'm wondering how I can set a default Value for String[].
@Value("${blacklist}")
private String[] blacklist;
In runtime the list is filled via my application.yml. In Testcases it is null
and I will not set any value for each Testcase.
Furthermore if there are no entries in die application.yml it have to be an empty array.
Usage:
for (String varToRemove : blacklist) {
vars.remove(varToRemove );
}
Pls no answers like "Why you do not just null-check it?". I want to know how to set the default value :)
Upvotes: 1
Views: 4465
Reputation: 3
In my test ,this works in Spring Boot 2.3
@Value("${blacklist:aa,bb,cc}")
private String[] blacklist; // got blacklist = {aa,bb,cc} in runtime.
and this doesn't work.
@Value("${blacklist:}")
private String[] blacklist = new String[]{"aa","bb","cc"}; // got blacklist = {} in runtime.
Upvotes: 0
Reputation: 182
I was so concentrated on the Annotation that I forgot the simplest way (and it works):
@Value("${blacklist:}")
private String[] blacklist= new String[0];
Upvotes: 4
Reputation: 21
Something like this should work:
@Value("#{blacklist ?: '1,2,3'}")
Taken from: https://www.mkyong.com/spring3/spring-value-default-value/
Upvotes: 2