如何在同一条分支通过Maven构建不同配置的开发及生产环境项目
Maven单分支多环境配置实现方案
核心通过Maven原生的Profile机制配合maven-resources-plugin完成不同环境配置文件的自动拷贝,具体配置步骤如下:
1. 新增环境Profile定义
编辑项目根目录的pom.xml文件,在<project>根节点下新增<profiles>配置(如果已有则直接追加):
<profiles> <!-- 原有APIServer Profile保留即可 --> <profile> <id>APIServer</id> <!-- 原有APIServer的配置保持不变 --> </profile> <!-- 开发环境Profile --> <profile> <id>DEV</id> <!-- 可选配置:本地开发默认激活DEV环境 --> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- 定义开发环境配置文件所在路径 --> <env.config.path>${project.basedir}/config/dev</env.config.path> </properties> </profile> <!-- 生产环境Profile --> <profile> <id>PROD</id> <properties> <!-- 定义生产环境配置文件所在路径 --> <env.config.path>${project.basedir}/config/prod</env.config.path> </properties> </profile> </profiles>
2. 配置资源拷贝插件
在pom.xml的<build><plugins>节点下追加maven-resources-plugin配置,实现构建时自动拷贝对应环境的配置文件到目标位置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> <executions> <execution> <id>copy-env-config</id> <!-- 配置在资源处理阶段执行拷贝,晚于默认资源拷贝动作,会自动覆盖同名文件 --> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <!-- 配置文件要拷贝到的目标位置,此处为打包后的classes根目录,可根据实际需求调整 --> <outputDirectory>${project.build.outputDirectory}</outputDirectory> <resources> <resource> <!-- 读取当前激活Profile对应的配置目录 --> <directory>${env.config.path}</directory> <filtering>false</filtering> <!-- 如果需要只拷贝指定后缀的文件可加includes配置,例如 <includes> <include>*.yml</include> <include>*.properties</include> </includes> --> </resource> </resources> </configuration> </execution> </executions> </plugin>
3. 构建验证
配置完成后即可使用你要求的命令完成对应环境的构建:
- 开发环境构建:
mvn -U clean install -PDEV,APIServer - 生产环境构建:
mvn -U clean install -PPROD,APIServer
如果需要验证当前激活的Profile是否正确,可执行命令mvn help:active-profiles -PDEV,APIServer查看输出结果。
注意:如果原有项目
src/main/resources目录下存在和config目录中同名的配置文件,上述配置会自动用环境专属配置覆盖默认配置,无需额外调整。
内容的提问来源于stack exchange,提问作者Ravi Teja RVN
相关产品推荐
相关产品推荐

