Spring Boot打war包时如何按Maven环境仅打包对应application配置文件
问题描述
需为Spring Boot项目创建多套application配置文件,并在生成的war包中仅纳入匹配环境的指定配置文件。
当前现状
已可正常生成war包,但无法将指定环境的配置文件打入包内:已配置多套Maven Profile,且创建了遵循application-env.properties命名规则的环境配置文件(env对应dev、cert等环境),所有配置文件均存放于src/main/resources目录下;但即便通过-Dspring.profiles.active=cert指定激活的Profile,仍无法选定对应配置文件打入war,最终生成的war包含了全部配置文件。
已配置的Maven Profile代码
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <build.profile.id>dev</build.profile.id> <packaging.type>jar</packaging.type> <spring.profiles.active>dev</spring.profiles.active> </properties> </profile> <profile> <id>cert</id> <properties> <build.profile.id>cert</build.profile.id> <spring.profiles.active>cert</spring.profiles.active> <packaging.type>war</packaging.type> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> </dependencies> </profile> </profiles>
相关截图

问题根因
src/main/resources目录下的所有文件默认会被全部收集打入构建产物,该过程和Maven Profile的激活、Spring运行时Profile的指定没有直接关联。之前传入的-Dspring.profiles.active=cert是应用运行时的参数,不会影响Maven打包阶段的资源收集逻辑,因此会出现所有环境配置文件被全部打入包的情况。
解决方法
- 在pom.xml的
<build>节点下配置资源打包过滤规则,根据激活的Maven Profile筛选需要打入包内的配置文件:
<resources> <!-- 第一部分:收集所有常规资源,排除所有多环境配置文件 --> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <excludes> <exclude>application-*.properties</exclude> </excludes> </resource> <!-- 第二部分:单独加入当前激活Maven Profile对应的环境配置文件 --> <resource> <directory>src/main/resources</directory> <includes> <include>application-${build.profile.id}.properties</include> </includes> </resource> </resources>
规则逻辑说明:该配置拆分为两个独立的资源收集块,避免同一资源块内exclude优先级高于include的问题,最终效果是包内只保留通用主配置、其他静态资源,以及当前激活环境对应的单个配置文件,其余环境的配置会被完全排除,不会打入构建产物
- 调整打包命令,通过Maven的Profile激活参数指定环境,而非传入Spring运行时参数:
# 激活cert环境的Maven Profile,生成仅包含cert配置的war包 mvn clean package -P cert
- 可选优化:删除各Maven Profile中冗余的
spring.profiles.active属性。由于打包阶段已经仅保留了对应环境的配置文件,无需再通过参数强制指定Spring激活的Profile,可避免配置冲突。
内容的提问来源于stack exchange,提问作者Antonio Diaz
相关产品推荐
相关产品推荐

