#Conditional default value based on Spring profile - spring

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.

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.

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

Setting spring.profiles.active to value with variables in application.properties

Is it possible to set spring.profiles.active in application.properties to a value containing other variables? Apparently, I cannot get this to work.
Here is what I want:
one=${APP_ONE:foo}
two=${APP_TWO:bar}
spring.profiles.active=${one},${two}
Here, also the environment variables APP_ONE and APP_TWO should be interpreted and end up in spring.profiles.active.
I then want to be able to refer to this in applicationContext.xml in a <beans profile="one"> tag.
Sorry, if I'm not clear enough here but I do not know how to be more precise.
It is possible. However you cannot define the variable for spring.profiles.active in the same(or lower precedence) of the property source order in which spring checks. The order is mentioned here.
In your case, you have tried to interpolate the variables "within" the same property source. You can do it for other properties but not for spring.profiles.active, because it is probably picked up first to enable spring to decide what other profile specific properties needs to be checked.
If you change your application.properties to
spring.profiles.active=${APP_ONE:foo},${APP_TWO:bar}
and then set the APP_ONE,APP_TWO variable with a higher property source order (for example command line arguments). It should set the profiles as expected.
I did not understand the second part of your question, but if you want to know what profiles are active, programmatically, you can simply autowire Environment and call the corresponding methods.
#Autowired
Environment env;
Environment has methods like
String[] getActiveProfiles()
String[] getDefaultProfiles() //and
boolean acceptsProfiles(String... profiles)

How to set Spring camel case property with uppercase environment variable?

I have some code to load a value as such in my Spring application:
#Component
public class MyElasticRestService {
#Value("${elasticApi.baseURL}")
private String elasticApiBaseUrl;
According to the Spring docs, I should be able to use a relaxed binding that comes from an uppercase environment variable such as ELASTIC_API_BASE_URL or ELASTICAPI_BASEURL. But I'm confused which is correct. Both don't seem to work so I am wondering how to debug what is actually picked up.
I've loaded Spring Boot Actuator to view the configprops endpoint. But it doesn't have anything on the elasticApi prefix.
What should the correct environment variable be and how can I see how it gets translated and picked up by the application?
The #Value annotation doesn't support relaxed bindings. Therefore you could use a class annotated with #ConfigurationProperties or you use a RelaxedPropertyResolver to get the value from the environment.
According to https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-vs-value, it is now very possible simply with #Value as long as you use kebab-case (all lower case with dash) for the name e.g. #Value("config.refresh-rate")
Instead of trying to make it an UPPER_SNAKE_CASE, you can put it in your application.yaml file, this way:
elasticApi.baseURL: ${ELASTIC_API_BASE_URL:defaultvalue}
or this way doesn't really matter:
elasticApi:
baseURL: ${ELASTIC_API_BASE_URL:defaultvalue}

Resources