Spring @Value annotated method, use default value when properties not available

26,539

Solution 1

To answer your question exactly...

@Value("${secret:secret}")
private String ldapSecret;

And a few more variations are below for completeness of the examples...

Default a String to null:

@Value("${secret:#{null}}")
private String secret;

Default a number:

@Value("${someNumber:0}")
private int someNumber;

Solution 2

Just use:

@Value("${secret:default-secret-value}")
private String ldapSecret;

Solution 3

@Value and Property Examples
To set a default value for property placeholder :

${property:default value}
Few examples :

//@PropertySource("classpath:/config.properties}")
//@Configuration

@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;

@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongodbUrl;

@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
Share:
26,539
RenatoIvancic
Author by

RenatoIvancic

I am developing back-end systems (microservices, monoliths, integrations, core libraries, customized build tools) in the financial space. I strive to maintain extensible architecture and high quality code. To tame my pet peeve with Gradle I created Udemy Gradle Plugin Development Course (still FREE!) where I gather and share acquired knowledge. I enjoy digging deep into Gradle to understand dependency resolution, running all kinds of tests, configuration and creation of custom plugins.

Updated on February 14, 2020

Comments

  • RenatoIvancic
    RenatoIvancic about 4 years

    Situation

    I am injecting properties from .properties file into fields annotated with @Value. However this properties present sensitive credentials, so I remove them from repository. I still want that in case someone wants to run project and doesnt have .properties file with credentials that default values will be set to fields.

    Problem

    Even if I set default values to field itself I get exception when .properties file is not present:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxx': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'secret' in string value "${secret}"
    

    Here is the annotated field:

     @Value("${secret}")
     private String ldapSecret = "secret";
    

    I expected in this case just plain String "secret" would be set.