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

Time:09-08

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

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?

CodePudding user response:

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) {
}

CodePudding user response:

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!

  • Related