简体   繁体   English

使用带有 Spring 引导的 dotenv 文件

[英]Using dotenv files with Spring Boot

I'd like to use dotenv files to configure my Spring Boot application.我想使用 dotenv 文件来配置我的 Spring 引导应用程序。

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.RubyNode世界中,我只是创建.env文件并将所有内容从那里加载到应用程序环境。

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.我不喜欢为我的应用程序创建单独的配置文件等。我只想将我在文件中指定的任何环境变量加载到我的应用程序中。

I have built a proper integration between Spring and dotenv .我已经在 Spring 和dotenv之间建立了适当的集成。

Follow this thread to understand the motivation.按照这个线程来了解动机。 And then review the library:然后查看库:

Check out the spring-dotenv library here:在此处查看 spring-dotenv 库:
https://github.com/paulschwarz/spring-dotenv 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:该库包含一个示例应用程序来向您展示如何使用它,您会看到与 Spring 的集成非常自然:

https://github.com/paulschwarz/spring-dotenv/tree/master/application/src/main/resources 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 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.让您的代码完全不知道 dotenv,以便您继续使用普通的 Spring 技术引用您的 application.yml/application.properties 文件。 No funny business.没什么好笑的。

There's actually a java port of 'dotenv' tool.实际上有一个“dotenv”工具的 java 端口。

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

In spring boot just do that in application.yml在 spring 启动中,只需在 application.yml 中执行此操作

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

username: ${USERNAME}

or if you use application.properties或者如果您使用 application.properties

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

Then @value and all other stuff will work然后@value 和所有其他的东西都会起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM