Skip to content
Advertisement

Spring Boot App does not recognize environment variables in application.yml file

there. I’m new to Java Spring Boot and I’m trying to set environment variables in application.yml.

I’ve added dotenv maven dependency:

JavaScript

I’ve set variables in the .env file:

JavaScript

And in my application.yml:

JavaScript

While running application I’m getting jdbc error:

java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, ${SPRING_DATABASE_URL}

I’ve tried some solutions like:

JavaScript

or in application.yml:

JavaScript

or

JavaScript

or

JavaScript

Am I doing something wrong or missing? I appreciate your help, thank you.

Advertisement

Answer

I recently ran in a similar issue and wanted to set environment variables via .env with application.yml – here is what I found out:

First, as you mentioned you have to add the java-dotenv dependency to pom.xml:

JavaScript

Then create your .env file in the root of your project (where pom.xml is located) and write your environment variables like e.g. ENV_PORT=8081.

Before you can use this environment variable, you have to “bind” the content of the .env file with Spring Boot when you start the app to make it globally available. According to this thread, this can be achieved by simply altering your Main entry point of spring (where you init the framework) like so:

JavaScript

That’s it, now you can reference to your environment variables in application.yml like so:

JavaScript

Hope this helps! If you are interested, here is also a full working example where I am using this approach.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement