在实际开发中,有多种环境配置,开发环境、测试环境、准生产环境、生产环境等。在不同的环境下,某些配置文件信息是不一样的,如接口地址、数据库连接配置等。为了避免频繁的修改配置文件,需要简单的切换配置文件,这里记录一下过程。
配置多环境
1.命名格式需要符合 application-xxx.properties(yml同理),如下
2.需要一个主配置文件application.properties,这里边可以写公共的各个环境不会变化的配置信息,然后通过如下配置动态切换配置文件
spring.profiles.active=@spring.profiles.active@
3.pom文件配置
在配置文件中添加如下配置
<profiles>
<!--本地环境-->
<profile>
<id>local</id>
<properties>
<spring.profiles.active>local</spring.profiles.active>
</properties>
<!--默认激活状态-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
<!--准生产-->
<profile>
<id>pre</id>
<properties>
<spring.profiles.active>pre</spring.profiles.active>
</properties>
</profile>
<!--生产 -->
<profile>
<id>prd</id>
<properties>
<spring.profiles.active>prd</spring.profiles.active>
</properties>
</profile>
</profiles>
在< build/>里添加,打开过滤开关,和maven插件
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>logback.xml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>logback.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
</configuration>
<version>2.0.0.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
这样的话,maven打包就可以根据选择动态的切换环境了,-P {环境}
mvn package -P local|qa|pre|prd
//@spring.profiles.active@ 会根据选择动态变化
spring.profiles.active=@spring.profiles.active@