Waize
Waize

Reputation: 182

Spring @Value default value for String[]

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

Answers (3)

user3671718
user3671718

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

Waize
Waize

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

Kiru
Kiru

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

Related Questions