Vova Rozhkov
Vova Rozhkov

Reputation: 1732

Using dotenv files with Spring Boot

I'd like to use dotenv files to configure my Spring Boot application.

What is the best way to do this?

In Ruby or Node world, I just creating .env file and it loads all stuff from there to application environment.

I don't like to create separate profiles for my app etc. I just want to load any environment variables I specified in file into my app.

Upvotes: 22

Views: 28439

Answers (4)

siddhu gorli
siddhu gorli

Reputation: 11

by importing properties in application.yml/properties file


spring:
  config:
    import: optional:file:.env[.properties]
  datasource:
    url: ${DB_URL}
    ....

Upvotes: 1

Paul Schwarz
Paul Schwarz

Reputation: 1958

I have built a proper integration between Spring and dotenv.

Latest releases:

Follow this thread to understand the motivation. And then review the library:

Check out the spring-dotenv library here:
https://github.com/paulschwarz/spring-dotenv

The library includes a sample application to show you how to use it, and there you see that the integration with Spring is very natural:

https://github.com/paulschwarz/spring-dotenv/tree/master/application/src/main/resources

I stuck to two principles in designing this library:

  1. https://12factor.net/config
  2. Allow your code to be completely unaware of dotenv so that you continue to reference your application.yml/application.properties files using the normal Spring techniques. No funny business.

Upvotes: 19

Bruno Lee
Bruno Lee

Reputation: 1977

In spring boot just do that in application.yml

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

username: ${USERNAME}

or if you use application.properties

spring.config.import=optional:file:.env[.properties]
username=${USERNAME}

Then @value and all other stuff will work

Upvotes: 27

Maksym Govorischev
Maksym Govorischev

Reputation: 776

There's actually a java port of 'dotenv' tool.

https://github.com/cdimascio/dotenv-java

Upvotes: 3

Related Questions