Set the default value for null in Spring @Value in java.util.Set variable

Having an interesting problem with Spring @Value annotation using SpEL. Setting the default value for null works for the String variable. However, for the Set variable this is not so.

So this works (varStr is null):

@Value("${var.string:#{NULL}}")
private String varStr;

while it is not (now varSet contains one element with "# {NULL}"):

@Value("#{'${var.set:#{NULL}}'.split(',')}")
private Set<String> varSet;

The question is how to make this work using the Set variable, so by default it will be null.

Your help will be greatly appreciated.

+4
source share
3 answers

@Value Set. init @PostConstruct Set. Spring, , ( null), ( @Value). , .

:

@Value("${some.prop:}")
private String[] propsArr;
private Set<String> props;

@PostConstruct
private void init() throws Exception {
    props = (propsArr.length == 0) ? null : Sets.newHashSet(propsArr);
}

. , null, . Null , . - .

BTW - Sets.newHashSet(...) Google Guava library. .

+4

PropertySourcesPlaceholderConfigurer. bean .

@Configuration
@ComponentScan
class ApplicationConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
  PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
  c.setNullValue("");
  return c;
}

: http://blog.codeleak.pl/2015/09/placeholders-support-in-value.html

null.

+2

If you do not find an elegant solution to get around this, you can enter the property in your contructor as String, and then Split()yourself or by default null.

class Foo {

    private Set<String> varSet;

    public Foo(@Value("${var.string:#{NULL}}") String varString) {
        varSet = (varString == null) ? null : new HashSet<>(Arrays.asList(varString.split(",")));
    }
}
0
source

Source: https://habr.com/ru/post/1667818/


All Articles