application.properties中的spring boot .env变量

Dra*_*wka 4 environment-variables pom.xml maven spring-boot application.properties

我已经创建了 .env 文件,我现在在其中保存变量,我希望它们在我的 application.properties 中定义,但这不起作用。我需要添加什么来获取变量。

.env 文件

MYSQLDB_USER=root
MYSQLDB_ROOT_PASSWORD=root
Run Code Online (Sandbox Code Playgroud)

应用程序属性

spring.profiles.active = dev
Run Code Online (Sandbox Code Playgroud)

应用程序-dev.properties

# mysql database properties
spring.datasource.url = jdbc:mysql://localhost:3306/testdb?useUnicode=true&serverTimezone=UTC&server&createDatabaseIfNotExist=true
spring.datasource.username = ${MYSQLDB_USER}
spring.datasource.password = ${MYSQLDB_ROOT_PASSWORD}
        
# hibernate properties
spring.jpa.hibernate.ddl-auto = create
spring.jpa.show-sql = true
Run Code Online (Sandbox Code Playgroud)

Sco*_*ick 18

这不会自动发生。您可以通过将其添加到您的application-dev.properties

spring.config.import=optional:file:.env[.properties]
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用额外的库来添加对此的支持,例如https://github.com/paulschwarz/spring-dotenv

一些关于在 Spring Boot 中添加对此的支持的讨论,但这并不是一个高优先级。

  • `.env` 文件必须放置在哪里?`[.properties]` 在做什么? (3认同)
  • 在此示例中,应用程序运行时,“.env”位于当前工作目录中。如有必要,您可以添加文件的路径。`[.properties]` 告诉 Spring Boot 将文件视为 Java 属性文件(而不是 YAML 文件)。如果没有文件扩展名,Spring Boot 就无法识别没有此提示的格式。 (2认同)