springboot项目maven多环境打包配置
前言
针对springboot项目的打包,我们往往针对不同环境准备了多份配置文件,比如:application-dev.yml,application-prod.yml等。如果需要更加的灵活地在打包时针对不同的环境将对应的配置文件打包,甚至基于不同的环境运行不同的maven插件呢?本文介绍通过maven的profiles属性控制多环境下的maven配置
maven build resources
我们先讲解一下maven build resources属性,该属性允许我们自定义打包的路径,默认情况下,maven插件会帮我们把所有src/main/resource下的资源打进jar包,而这个属性允许我们对资源进行筛选与过滤
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>application.yml</include>
<include>*-${profiles.active}.yml</include>
<include>**/*</include>
<include>**/**/*</include>
</includes>
<excludes>
<exclude>lib/*</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
<targetPath>BOOT-INF/classes/</targetPath>
<includes>
<include>application.yml</include>
<include>*-${profiles.active}.yml</include>
<include>**/*</include>
<include>**/**/*</include>
</includes>
<excludes>
<exclude>lib/*</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>${basedir}/src/main/resources/lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
比如上述配置中
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>application.yml</include>
<include>*-${profiles.active}.yml</include>
<include>**/*</include>
<include>**/**/*</include>
</includes>
<excludes>
<exclude>lib/*</exclude>
</excludes>
<filtering>false</filtering>
</resource>
该模块表示:将src/main/resources下的主配置文件、匹配*-${profiles.active}.yml
正则的配置文件、一级目录、二级目录打包到target下,并排除lib下的内容
maven profiles
然后我们定义一组profiles
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.active>*</profiles.active>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
</profiles>
我们定义了多个profile,并为每一个profile定义了参数profiles.active,即我们resource中使用的${profiles.active}
变量,这里就可以明白我们通过指定不同的profile便可以将对应的配置文件打包。示例中id为dev的profile定义**profiles.active=***表示开发环境中我们允许打包所有的配置文件
mvn install -P
那么如何在maven打包的时候激活对应的profile呢,mvn -P命令即可,比如mvn install -Pdev即表示激活id=dev的profile,此时所有的配置文件会被打包,test,prod同理
其他
同样的maven profile不止可以定义变量,还可以定义plugin(插件)等属性都可以在这定义,我们可以在不同的maven profile中激活不同的插件。比如整合docker插件去自动推送镜像,我们可以为需要此插件功能的环境定义一套profile,比如id=docker,这样我们在执行mvn install -Pdocker
命令时,便可以同时将镜像推到仓库啦~