1

I'm running a SpringBoot application that needs environmental variables. How can I use the values of variables declared in an .env file inside the application.properties file in spring-boot?

.env

PORT=12345

application.properties

server.port=$PORT
Vito Lipari
  • 795
  • 8
  • 35
  • check this link which shows how to dynamically update the application properties. You can get the env properties using System class. https://stackoverflow.com/questions/41192085/how-to-maintain-update-application-properties-dynamically-in-spring#:~:text=You%20can%20do%20something%20like,same%20file%20using%20the%20FileOutputStream%20. – John Sep 06 '21 at 21:50

2 Answers2

1

I think this will work, as it worked in my system.

I am using application.properties file for configuration.

In .env file add PORT in key value pair

PORT=12345

In application.properties file add spring.config.import to import the .env file in application.properties

spring.config.import=optional:file:.env[.properties]

server.port=${PORT}

To access the PORT value in application.properties use ${YOUR_ENVIRONMENT_VARIABLE_NAME} for expected value in server.port.

0

Just add @PropertySource that points to the .env file.

Alexander.Furer
  • 1,817
  • 1
  • 16
  • 24