Search code examples
javaspringspring-annotations

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


Solution

  • @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();