常用的环境有开发环境dev、测试环境test、验收环境uat、生产环境prod。多环境配置可以有效的进行数据库及其他数据的配置,是常用的手法。
多环境配置常用的有两种方式:
方式一、复制多个application.properties文件,并根据环境重命名。
复制多个不同环境的配置文件 命名例如:application-dev.properties、application-test.properties、application-uat.properties、application-prod.properties
然后在application.properties配置文件
添加如下内容,
##指定环境
spring.profiles.active=prod
方式二、将不同环境的配置文件放在不同的文件目录下。
先在resource文件中新建目录结构,开发环境是dev目录,测试环境是test目录,验收环境是uat目录,生产环境是prod目录。每个目录下面都有application.properties文件。
在不同环境的配置文件添加如下配置:
示例:
##开发环境配置文件
multiple.environment.configure=dev environment
##测试环境配置文件
multiple.environment.configure=test environment
然后启动类module中的pom.xml文件中配置如下:
<profiles>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active><!-- 配置文件目录的名字 -->
</properties>
<activation>
<activeByDefault>true</activeByDefault> <!-- 默认启动dev环境 -->
</activation>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<!-- uat环境 -->
<profile>
<id>uat</id>
<properties>
<profiles.active>uat</profiles.active>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
</profiles>
<build>
<finalName>app</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<!-- 打包时删除以下目录 -->
<excludes>
<exclude>dev/*.properties</exclude>
<exclude>test/*.properties</exclude>
<exclude>uat/*.properties</exclude>
<exclude>prod/*.properties</exclude>
</excludes>
</resource>
<resource>
<!-- 这个就是切换不同环境的路径,${profiles.active}profiles.active,可自定义 -->
<directory>src/main/resources/${profiles.active}</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>
true
</skip>
</configuration>
</plugin>
</plugins>
</build>
以上打包我是通过IDEA的maven窗口来打包的
也可以使用maven命令打包:
开发环境打包
mvn clean package -P dev
测试环境打包
mvn clean package -P test
生产环境打包
mvn clean package -P prod