Spring Boot中如何从.env文件传递布尔值至application.yaml?
解决Spring Boot从.env读取布尔值到application.yaml的问题
错误根源很清晰:Spring Boot默认不会自动加载项目根目录的.env文件,导致application.yaml中的${SHOW_SQL}未被替换为实际的true,反而把字符串"${SHOW_SQL}"直接传给布尔类型属性,触发类型转换失败。
以下是几种可行的解决方法:
方法一:用java-dotenv库加载.env(适配测试场景)
- 在
pom.xml中添加依赖:
<dependency> <groupId>io.github.cdimascio</groupId> <artifactId>java-dotenv</artifactId> <version>5.2.2</version> <scope>test</scope> </dependency>
- 在测试基类中提前加载.env变量到系统属性:
import io.github.cdimascio.dotenv.Dotenv; import org.junit.jupiter.api.BeforeAll; public class BaseTest { @BeforeAll static void loadEnvVariables() { Dotenv dotenv = Dotenv.load(); dotenv.entries().forEach(entry -> System.setProperty(entry.getKey(), entry.getValue())); } }
让所有测试类继承该基类,执行mvn test时就能正确解析${SHOW_SQL}。
方法二:通过Maven命令或插件注入环境变量
方式1:命令行直接传递
执行测试时手动传入环境变量:
mvn test -DSHOW_SQL=true
方式2:Maven插件配置
修改pom.xml的maven-surefire-plugin,让测试阶段自动读取系统环境变量:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.1.2</version> <configuration> <environmentVariables> <SHOW_SQL>${env.SHOW_SQL}</SHOW_SQL> </environmentVariables> </configuration> </plugin>
使用前需确保系统环境变量已通过dotenv-cli等工具加载.env中的SHOW_SQL=true。
方法三:用Spring Cloud Bootstrap自动加载.env(全场景适配)
如果项目依赖Spring Cloud,可通过bootstrap配置自动加载.env:
- 添加Spring Cloud Bootstrap依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> </dependency>
- 创建
bootstrap.yaml文件,配置.env加载路径:
spring: config: import: optional:file:.env[.properties]
这样Spring Boot启动(含测试)时会自动读取.env变量,application.yaml中的${SHOW_SQL}会被正确解析为布尔值。
内容的提问来源于stack exchange,提问作者Alberto Morreale
相关产品推荐
相关产品推荐

