如何通过Maven加载环境变量文件?求合适插件方案
解决Maven加载环境变量文件的实用方案
方案1:用Properties Maven Plugin读取.env文件
这个插件可以直接解析.env格式文件,将变量注入到Maven属性中,供测试、构建全环节使用,结合Profiles可轻松切换环境。
配置步骤
- 在pom.xml中添加插件与多环境Profile:
<profiles> <!-- 开发环境Profile --> <profile> <id>dev</id> <properties> <env.file>src/main/resources/.env.dev</env.file> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0.0</version> <executions> <execution> <phase>initialize</phase> <goals> <goal>read-project-properties</goal> </goals> <configuration> <files> <file>${env.file}</file> </files> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <!-- 生产环境Profile --> <profile> <id>prod</id> <properties> <env.file>src/main/resources/.env.prod</env.file> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0.0</version> <executions> <execution> <phase>initialize</phase> <goals> <goal>read-project-properties</goal> </goals> <configuration> <files> <file>${env.file}</file> </files> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
- 传递变量给测试环节(Surefire插件):
如果需要让测试用例通过系统属性读取变量,在Surefire插件中添加配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <configuration> <systemPropertyVariables> <db.url>${DB_URL}</db.url> <db.username>${DB_USERNAME}</db.username> </systemPropertyVariables> </configuration> </plugin>
- 使用方式:
运行Maven命令时指定对应Profile即可,比如开发环境测试:mvn clean test -P dev,生产环境打包:mvn clean package -P prod
方案2:直接通过Surefire加载.env文件(仅测试场景)
Surefire插件本身支持通过environmentVariablesFile参数加载.env文件,无需额外插件,适合仅测试环节需要变量的场景。
配置示例
<profiles> <profile> <id>dev-test</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <configuration> <environmentVariablesFile>src/main/resources/.env.dev</environmentVariablesFile> </configuration> </plugin> </plugins> </build> </profile> </profiles>
运行测试命令:mvn test -P dev-test,测试用例可通过System.getenv("DB_URL")直接读取环境变量。
方案3:结合Resources插件替换配置文件占位符
如果项目使用application.properties这类配置文件,可通过Profiles配合Resources插件替换占位符,实现环境切换。
配置步骤
- 在配置文件中使用占位符:
db.url=${DB_URL} db.username=${DB_USERNAME}
- 在pom.xml的Profile中定义变量(或结合Properties插件读取.env文件):
<profile> <id>dev</id> <properties> <DB_URL>jdbc:mysql://localhost:3306/dev_db</DB_URL> <DB_USERNAME>root</DB_USERNAME> </properties> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </profile>
构建时Maven会自动替换配置文件中的占位符,生成对应环境的配置。
注意事项
- 将.env文件添加到
.gitignore,避免敏感信息提交到版本控制 - 尽量使用插件的最新稳定版本,规避兼容性问题
- 多模块项目建议将插件配置放到父pom中,统一管理
内容的提问来源于stack exchange,提问作者BUKTOP
相关产品推荐
相关产品推荐

