Spring provides the powerful annotation @value to set a default value expression for a field or method/constructor parameter. @value is mainly used to inject a property value from the applications.properties file into a Spring bean. This tutorial will show how to fix the exception thrown by Spring when you want the use a optional Spring @value :
java.lang.IllegalArgumentException: Could not resolve placeholder ‘foo.property’ in string value “${foo.property}”
1- Providing a default value
Sometimes it’s useful to provide a default value of the property. It can be achieved by following this rule :
1 |
@Value("${property_name:default_value}") |
example :
1 2 |
@Value("${proxy.port:80}") private int proxyPort; //80 |
When no value of proxy.port is given in the context, Spring will set the value of proxyPort to 80.
2- Null value
But sometimes, we want to set the property to null when no value is given. This can be achieved using Spring Expression Language (SpEL) like below :
1 |
@Value("${property_name:#{null}") |
example :
1 2 |
@Value("${proxy.host:#{null}}") private String proxyHost; //null |
References