Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 743
RenatoIvancic Avatar asked Apr 05 '17 18:04

RenatoIvancic


People also ask

How do I change the default value in spring boot model?

To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.

Can I use @value in a method?

We know now, that we can use the @Value annotation for methods as a global value or as a parameter value.

What is the use of @value annotation in spring boot?

One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL).


2 Answers

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;
like image 177
Bernie Lenz Avatar answered Oct 05 '22 17:10

Bernie Lenz


Just use:

@Value("${secret:default-secret-value}")
private String ldapSecret;
like image 39
fps Avatar answered Oct 05 '22 18:10

fps