'Spring Boot Properties - ternary condition based on Env Variable
I want to set conditional variables for kafka in spring boot, based on the environment variable.
I have tried this combination:
consumer:
auto-offset-reset: #{${ENV_VARIABLE:}=="" ? "latest" : "earliest"}
Also all the other combinations with single and double quotes. In some cases this property is filled with the full expression (Without parsing), and in some with just empty string "" .
Is there a possibility to achieve that?
My goal is to set the auto-offset-reset: latest or earliest
Solution 1:[1]
The spring boot docs state that:
SpEL expressions from application property files are not processed at time of parsing these files and populating the environment.
Anyway, Spring Boot provides a number of ways to have properties based on the environment.
Based on this and your other recent question, the way you seem to be trying to achieve this would likely result in environment-based logic being spread throughout the application code, which would probably be hard to maintain and troubleshoot.
The proper way I know to do this is to set the spring application profile through an environment variable, such as spring.profiles.active=test
You can then have a base application.yml with default or local properties, and override them in a application-test.yml, which will be loaded when the profile env variable is set.
With this you get a nice log at startup stating what is the active profile, which makes it a lot easier to troubleshoot whether the correct environment variables were applied:
The following profiles are active: test
Summing up:
application.yml
spring:
kafka:
consumer:
auto-offset-reset: earliest
application-test.yml
spring:
kafka:
consumer:
auto-offset-reset: latest
Environment variable
spring.profiles.active=test
You should have one application-{env}.yml for each environment e.g. stage, prd, qa. You can also have one for local, but then you have to add the environment variable in your IDE runner.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
