Can I define an application.properties file value as optional - spring-boot

In my application.properties file I would like to have an optional value. Such as spring.datasource.url=${value} but optional
Is this possible?

You can define a property as "optional" by giving it a default value where you inject it.
For example:
#Value("${spring.datasource.url:null}")
private String springDatasourceURL;

Related

Spring boot picking #value from default properties file

I am using #value annotation in spring boot to read a property
#Value(value = "${propName:#{null}}")
private String prop;
And based on if it is null or driving some logic in my code. In my dev environment I want to keep it null so I don't add it in that property file (application-dev.properties). But instead of getting it as null, it is reading the value from default application.properties file.
Yes, this is the correct behavior based on Spring's property resolution. If you want to override it in your dev profile, simply add the property to your application-dev.properties, leaving the value empty. This will result in an empty String, not null, which you can convert to null with something like this:
#Value("${#{some_property == \"\"}:#{null}}")
private String prop;
It is probably a good idea to explicitly define these properties and give them values that make sense. Otherwise, you'll likely revisit this code in a few months and wonder what the heck is causing xyz.
You can read up on Spring and the order with which it resolves properties here but generally, you'd want to define variables that apply to all environments in your application.[properties][yaml], and then override them in the environment-specific properties files. In this case, it kind of sounds like this is a flag that's on or off depending on if the dev environment is set; you might consider something like this.
#Value("${property_to_drive_behavior:false}"
private Boolean prop;
This will default to false, so you don't need to add it to any properties file. If you want it set, override it in the environment-specific properties file. Booleans can be set in properties files using either the explicit true or false keywords or the values or 0 for false, 1 for true.
By default, property values of external configuration sources (such as application.properties files) are always injected directly into your beans by using the #Value annotation.
One solution to your problem is moving the propName property from application.properties to application-{profile}.properties.

#Conditional default value based on Spring profile

I have this in my Java code.If fieldOne is not present in properties file
1)In prod environment(application_prod.yml) --fieldOne value should be true
2)For all other environment (application_uat.yml/application_int.yml)--fieldOne value should be false.
How to achieve it?
#Value("${fieldOne:true}")
private String fieldOne;
You can use application.yml to provide a default value that's overridden by profile specific files.
The order in which spring evaluates external configuration is documented here.

How to read variable or concatenate one property in #Value annotation of spring boot

I have one POJO class which read properties from application.yaml file in spring boot. Here I need to set default value to groupId(to get when not given) based on combination of topic value and another string.
private String topic;
#Value("${topic}_test")
private String groupId;
I tried this but getting error as
Could not resolve placeholder 'topic' in value "${topic}_test
I create a variable and tried to access it in #Value but failed.
Please provide any suggestion to access this
Default value
Let's say you have a property like this in your application.yml file
topic: myFavoriteTopic
The code below will assign the value "myFavoriteTopic" to variable groupId if Spring is able to load the property with key topic from application.yml. If it's not, it will assign the default value "my default topic".
#Value("${topic:my default topic}")
private String groupId;
To set null as the default value, use:
#Value("${topic:#{null}}")
To use an empty String as the default value, use:
#Value("${topic:}")
Get key name from a variable
In your code snippet you have a String topic variable. For the Spring framework, this variable is not used in the property value retrieval. When you do #Value("${topic}"), "topic" is the name of the key that Spring will look for in application.yml. The name of the key cannot be determined at runtime based on the value of a Java variable. The reason is that properties can be loaded before the class code executes.
_test suffix
Also in your code snippet, you use #Value("${topic}_test"). What Spring does in this case is to concatenate "_test" to the value retrieved for property key topic. In my first example, groupId would be assigned "myFavoriteTopic_test".

Optional environment variables in Spring app

In my Spring Boot app's application.properties I have this definition:
someProp=${SOME_ENV_VARIABLE}
But this is an optional value only set in certain environments, I use it like this
#Value("${someProp:#{null}}")
private String someProp;
Surprisingly I get this error when the env. var doesn't exist
Could not resolve placeholder 'SOME_ENV_VARIABLE' in string value "${SOME_ENV_VARIABLE}"
I was expecting Spring to just set a blank value if not found in any PropertySource.
How to make it optional?
Provide a default value in the application.properties
someProp=${SOME_ENV_VARIABLE:#{null}}
When used like #Value("${someProp}), this will correctly evaluate to null. First, if SOME_ENV_VARIABLE is not found when application.properties is being processed, its value becomes the string literal "#{null}". Then, #Value evaluates someProp as a SpEL expression, which results in null. The actual value can be verified by looking at the property in the Environment bean.
This solution utilizes the default value syntax specified by the PlaceholderConfigurerSupport class
Default property values can be defined globally for each configurer
instance via the properties property, or on a property-by-property
basis using the default value separator which is ":" by default and
customizable via setValueSeparator(String).
and Spring SpEL expression templating.
From Spring Boot docs on externalized configuration
Finally, while you can write a SpEL expression in #Value, such
expressions are not processed from Application property files.
This work for me:
spring.datasource.url=jdbc:mysql://${DB_IP:localhost}:3306/app
spring.datasource.username=${SPRING_DATASOURCE_USERNAME:mylocaluser}
spring.datasource.password=${SPRING_DATASOURCE_PASSWORD:localpass}
Because this is probably interesting to others who come here, you can override any properties file w/ an env variable implicitly. Let's say you have property.
someapp.foo
Then you can define an env variable SOMEAPP_FOO (capital letters and . -> _ ) and spring will implicitly set the property from the env. variable.
Described further here: https://hughesadam87.medium.com/how-to-override-spring-properties-with-env-vars-82ee1db2ae78

Property in #ConfigurationProperties prefix

Is it possible to use a property in
#ConfigurationProperties(prefix = "${domain}.user")
This doesn't work. I just want to "prefix the prefix" with the value from another property from the same properties file. For example:
domain=${domain}
domain1.user.username=john
domain2.user.username=irene
The full prefix wanted would be domain1.user after filtering using "domain1" as a value for the domain property.
According to #ConfigurationProperties javadoc:
* Note that contrary to {#code #Value}, SpEL expressions are not evaluated since property
* values are externalized.

Resources