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

RenatoIvancic picture RenatoIvancic · Apr 5, 2017 · Viewed 17.9k times · Source

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.

Answer

Bernie Lenz picture Bernie Lenz · Apr 5, 2017

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;