Set a value to default when property is empty

Viewed 378

I have a property in a configuration file like:

@Value("${MAX_VALUE:#{100}}")
private int maxSize;

In a properties file I have:

MAX_VALUE=

I'm using Java configurations

@Bean
public EncryptablePropertyPlaceholderConfigurer defaultProperties() {
    final EncryptablePropertyPlaceholderConfigurer defaultProperties = new EncryptablePropertyPlaceholderConfigurer(
            textEncryptor());
    Resource[] resources = new ClassPathResource[] { new ClassPathResource(jobProperties)};
    defaultProperties.setLocations(resources);
    defaultProperties.setIgnoreUnresolvablePlaceholders(true);
    defaultProperties.setIgnoreResourceNotFound(true);
    defaultProperties.setSearchSystemEnvironment(true);
    return defaultProperties;
}

When the MAX_VALUE parameter is not set I would like it to use the default value. Currently it gives me a 'NumberFormatException: For input string: "" '

Is there anyway to accomplish this or would I have to remove the MAX_VALUE from the properties file to use the default?

3 Answers

You can't have empty string to int type, but you can change the type to Integer and have the null check with default value using spring expression language

@Value("#{'${MAX_VALUE}' ?: 0}")
private Integer maxSize;

The following SPEL expression seems to work for null (missing in application.yaml), empty value and valid numbers:

@Value("#{'${MAX_VALUE:}' matches '\\d+' ? '${MAX_VALUE:1}' : 100 }")
private int maxSize;

Here a String value is created from MAX_VALUE using an empty value as a default.

If this value matches an int (not-negative) pattern, it is used as is, otherwise a default value 100 is provided.

I did not realize Spring Expression Langauge supports terniary operators. I was able to solve the above issue with:

@Value("${MAX_VALUE != '' ? MAX_VALUE:#{100}}")
private int maxSize;

For more info on SpEL

Related