Spring 4 @Value, where the default property is a java system property

In Spring 4, using the @Value annotation, what is the correct way to specify a default system property if the specified property does not exist?

While this works for the case without default:

@Value("${myapp.temp}") private String tempDirectory; 

This does not work when I need the default:

 @Value("#{myapp.temp ?: systemProperties.java.io.tmpdir}") private String tempDirectory; 

And it does not:

 @Value("#{myapp.temp ?: systemProperties(java.io.tmpdir)}") private String tempDirectory; 

Both of them give me an exception while Spring is trying to create a bean:

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurationService': Invocation of init method failed; nested exception is java.lang.NullPointerException 

Can this be done?

+8
java spring
source share
3 answers

I tried the following and it worked for me:

 @Value("${myapp.temp:#{systemProperties['java.io.tmpdir']}}") private String tempDirectory; 

The missing parts for you, I believe, have not used ?: And needed #{} . According to this answer :

${...} is the property placeholder syntax. It can only be used for dereferencing properties.

#{...} is the SpEL syntax, which is much more capable and more complex. It can also handle property placeholders and more.

So basically what is happening, we are telling Spring to first interpret myapp.temp as property builder syntax using the ${} syntax. Then we use : instead of ?: (Which is called the Elvis operator ), since the elvis operator applies only to Spring Expression Language expressions, not the property builder syntax. The third part of our statement is #{systemProperties['java.io.tmpdir']} , which tells Spring to interpret the following expression as a Spring expression and allows us to get the properties of the system.

+9
source share

Try systemProperties['java.io.tmpdir'] .

This is a map, so if the key has a dot in the name, you must use [..]

+1
source share

For me, it works only with different property names (this property .name.a is the key with the value in my applications .properties and property.name.ba Environment-Variable), for example:

 @Value("${property.name.a:${property.name.b}}") 

The same names did not work for me as expected (loading the default when the first property is not present), for example:

 @Value("${property.name.a:${property.name.a}}") 
0
source share

All Articles