Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
Vladimir Rozhkov Avatar asked Oct 24 '19 21:10

Vladimir Rozhkov


People also ask

Can I use .env in spring boot?

It can be used to create command line applications in Spring Boot. The @SpringBootApplication annotation enables auto-configuration and component scanning. We inject the Environment in order to obtain the properties. logger.info("{}", env.

How do I use dotenv files?

To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .

How do you load properties file based on environment in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.

Should you commit .env files?

env files to version control (carefully) Many software projects require sensitive data which shouldn't be committed to version control. You don't want Bad Guys to read your usernames, passwords, API keys, etc.


2 Answers

I have built a proper integration between Spring and dotenv.

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.
like image 129
Paul Schwarz Avatar answered Oct 03 '22 05:10

Paul Schwarz


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

like image 43
Bruno Lee Avatar answered Oct 03 '22 05:10

Bruno Lee