1

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

2 Answers 2

6
@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();
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason first solution doesn't work in WildFly. If there are several values, it doesn't split them and takes whole string as the first element. Second solution works fine though. In Spring Boot both work.
5

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

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

2 Comments

Strange. This was my first guess, but there is info all over the internet, that if your list in property file is not in {1,2,3} format, then simple ${myapp.values} doesn't parse it correctly. That's why I didn't even try that and sticked with usage of split(,) which didn't allow to use : simple as that. Thank you, it works.
For some reason this doesn't work in WildFly. If there are several values, it doesn't split them and takes whole string as the first element. In Spring Boot it works properly though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.