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

Situation

I am inserting properties from a .properties file into fields annotated with @Value . However, these properties contain sensitive credentials, so I delete them from the repository. I still want, in case someone wants to run a project and does not have a .properties file with credentials, the default values โ€‹โ€‹will be set in the fields.

Problem

Even if I set the default values โ€‹โ€‹for the field itself, I get an exception when the .properties file is missing:

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 that in this case only a simple "secret" String would be set.

+5
source share
3 answers

To accurately answer your question ...

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

And a few more options below for completeness ...

By default, String is null:

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

The default number is:

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

Just use:

 @Value("${secret:default-secret-value}") private String ldapSecret; 
+4
source
 @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; 
0
source

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


All Articles