一.介绍
在中大型企业项目开发中,环境分离是必不可少的一步,然而现在的开发人员也只是有这个概念,还是有很多项目采用普通的方式,每次打包发布部署的时候改动一大堆的配置文件,有一个地方忘记改就相当于白更新了一次系统,这种修改配置文件完成环境更换的方式给我们带来了很多的困扰,浪费了我们很多宝贵的时间!早在Spring 3.1
版本就已经为我们提供了环境分离的相关注解配置方式,不过在传统的Spring项目中配置Profile
确实有点麻烦,在Spring
版本的不断更新直到后来SpringBoot
成长起来后Profile
已经能够很好支持项目配置环境分离。
二.使用
直接在resource目录下
载application.properties 中指定自己想要打包的环境使用 spring.profiles.active。
不管在指定的配置是哪个环境的都会把所有的配置都打入class中。
三.使用maven profiles只打入指定环境的配置。
配置:
<profiles>
<profile>
<!-- 内网开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
<!--<activation>-->
<!--<activeByDefault>true</activeByDefault>-->
<!--</activation>-->
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
</profiles>
--------------
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 资源根目录排除各环境的配置,使用单独的资源目录来指定 -->
<excludes>
<exclude>application-dev.properties</exclude>
<exclude>application-test.properties</exclude>
<exclude>application-prod.properties</exclude>
<exclude>application.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.properties</include>
<include>application-${profiles.active}.properties</include>
</includes>
</resource>
</resources>
在打包的时候排除所有的配置,使用自己指定的配置爱打包。
四.maven profiles 的使用
什么是profile,解决什么问题呢?举个例子。一般在开发项目的时候要有多个环境,如开发环境、测试环境、生产环境,他们的配置文件一般不同。当我们要向各个环境发布程序时,需要人工处理这些配置文件,这显然麻烦且易错。有了profile,一切问题就简单了。只要在maven打包时使用下面命令即可。
mvn clean package -Dmaven.test.skip=true -P prod
解释一下, -P prod 就是告诉maven要使用名字为prod的profile来打包,即所有的配置文件都使用生产环境(prod是自己定义的,在这里自定义为生产环境)。
多环境配置的时候可以是多个文件夹,也可以是多个文件。
<profiles>
<profile>
<!-- 内网开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
<!--<activation>-->
<!--<activeByDefault>true</activeByDefault>-->
<!--</activation>-->
</profile>
<profile>
<id>staging</id>
<properties>
<profiles.active>staging</profiles.active>
</properties>
</profile>
<profile>
<id>production</id>
<properties>
<profiles.active>production</profiles.active>
</properties>
</profile>
</profiles>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 资源根目录排除各环境的配置,使用单独的资源目录来指定 -->
<excludes>
<exclude>dev/*</exclude>
<exclude>production/*</exclude>
<exclude>staging/*</exclude>
<exclude>test/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
</resource>
</resources>