How to use environment variables with application.properties in spring boot?

Viewed 123

I am trying to configure my application.properties to take the value from the system variables I've set. The problem is that it won't work no matter what I do. I've tried using a custom class configuration with DataSource from this example still no success. All I was able to find on stackoverflow are links pointing to the official docs. Unfortunately that's a dead end since it doesn't say anything and there are no examples for what I'm trying to achieve. I also found examples like spring.datasource.url = ${SPRING_DATASOURCE_URL} and everyone is saying that spring will know how to automatically take the environment variables. Well surprise, it doesn't.

I also found examples like spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD:the_actual_password) or spring.datasource.url = #{SPRING_DATASOURCE_URL:#{'the_actual_url'}} which is totally not what I need and it's pretty useless if you ask me. I mean I could achieve the same thing writing spring.datasource.password = the_actual_password. The whole point is to hide the sensitive data..

Now, this being said I'll leave 2 screenshots with what I have. The reason why I am trying to achieve this is because when I'll push to GitHub I won't have to worry that my credentials or anything will be out in the open for everyone to see.

Here is how my environment variables look like:

Here is how application.properties look like:

Thank you in advance! And in case you have an answer to my question could you also let me know how can I achieve the same thing with environment variable but for the application.jwt properties?

2 Answers

Ok, the solution was pretty... stupid, I suppose, but here it is. The reason why it didn't worked is because the environment variables were defined after IntelliJ first opened as described here. It seems like everything is working fine now.

I managed to achieve the functionality that I wanted.

In other words this:

spring.datasource.url = ${SPRING_DATASOURCE_URL}
spring.datasource.username = ${SPRING_DATASOURCE_USERNAME}
spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD}
spring.datasource.driver-class-name = ${SPRING_DATASOURCE_DRIVERCLASSNAME}

Is now working perfectly.

Thank you for all your help!

Have you used the correct annotations?

Given Properties as such:

root.test = ${TEST.VAR:-Test}

Environment variable like:

TEST.VAR = Something

Configuration class:

@Configuration
@ConfigurationProperties(prefix = "root")
public class Test {
  private String test;

  public String getTest() {
    return test;
  }

  public void setTest(String test) {
    this.test = test;
  }

}

You can use Records by setting @ConfigurationPropertiesScan on your Main class

@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication{...}

Defining Record like so:

@ConfigurationProperties(prefix = "root")
public record Test (String test) {
}
Related