0
votes

So I have been trying to figure out how to use environment-variables in either application.properties or application.yaml. Since this works in countless frameworks (such as Laravel for example), I assumed this would also work in Spring Boot. Now as I have found out, this is not the case.

I saw a post about Spring Environment API, that started that the environment-variable SPRING_DATASOURCE_URL would be equivalent to setting spring.datasource.url inside my application. However, this also didn't work for me.

Is there any quick way that allows using variables that are declared inside a .env file?

I'd like to use it like this inside the application.properties if possible. spring.datasource.url=jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}

1
It works for environment or any other variables but there is no support for .env files as those aren't exposed as environment variables afaik.M. Deinum
Do you have an alternative solution for this? For example, I want to run it locally by running with configuration file, but when using it with docker, I want to set the properties via. OS Environment variables.trm217
you can have multiple profiles, set variable values as different for each profile and load them during startupbrijesh
Exposing regular environemt variables works out-of-the-box. It is only that .env file that isn't supported. A docker environment variable just works.M. Deinum
So if I want it to work with a pure application.properties file in dev and env-variables in prod, I can just create a appilaction-dev.properties with absolute values and a application-prod.properties that uses the ${VAR_NAME} syntax?trm217

1 Answers

1
votes

.env is way of Python. If you use spring cloud, you can read env variable from configServer then inject them into application.properties.

  1. add some dependency into pom.xml

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
  1. define a yml to locate config-server. for example, called myBootstrap.yml
spring:
  cloud:
    config:
      fail-fast: true
      uri: http://[config-server-git]
      name: cc
      profile: config
      label: maste
  1. define a file named cc-config.properties and push it into config-server git. The env variables are written in this properties.

  2. use below way to run application jar

java -jar [your-application-jar] --spring.cloud.bootstrap.location=myBootstrap.yml