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

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)

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.

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

Spring Boot EnvironmentPostProcessor overriding Command Line

I am using an EnvironmentPostProcessor, in particular the CloudFoundryVcapEnvironmentPostProcessor, in order to parse some environment variables and make them accessible as Spring properties.
When I run my application, the EnvironmentPostProcessor kicks in and creates the desired property variables as expected.
#Value("${vcap.services.test-service.name}") /* Example of a property loaded from PostProcessor. Works fine. */
However, when I try to set this property value explicitly using the command line, or properties file, the value that I specify does not override the value that is being populated by the EnvironmentPostProcessor. I would expect that overriding this property via the command line should take precedence.
vcap.services.test-service.name=TEST_VALUE Does not override.
Essentially, there seems to be nothing I can do in order to override the value set by this EnvironmentPostProcessor (command line, profiles, .properties files, spring.factories order definitions, etc)
Is there any way to override a property value created in an EnvironmentPostProcessor?
This is caused by CloudFoundryVcapEnvironmentPostProcessor adding a property source with a precedence that's higher than the method you're using to override properties: https://github.com/spring-projects/spring-boot/blob/v1.3.3.RELEASE/spring-boot/src/main/java/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.java#L126-L135
There is that block that sets this lower than command line args, were you using command line args or -D system properties?
You could try adding spring-boot-starter-actuator and hit the /env endpoint to see all property sources and their precedence, those appearing first have higher precedence than those appearing further down in the JSON. As a last resort you can create your own EnvironmentPostProcessor that's Ordered to execute after CloudFoundryVcapEnvironmentPostProcessor, that creates a property source with highest precedence.

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