Spring Boot 自带的多环境配置
创建不同环境的配置文件
application.yml
application-dev.yml
application-prod.yml
application-test.yml
配置文件的名称一定要是 application-name.properties 或者 application-name.yml 格式。
这个name可以自定义,用于区分环境名。
配置文件中指定环境,相当于默认环境,如果运行 jar 命令时没有指定,使用默认环境。
spring:
profiles:
active: dev
运行 jar 的时候指定
SpringBoot 内置的环境切换能够在运行 Jar 包的时候指定环境,下面命令指定了 prod 环境:
java -jar xxx.jar --spring.profiles.active=prod
Maven 的多环境配置
Maven本身也提供了对多环境的支持,不仅仅支持Spring Boot项目,只要是基于Maven的项目都可以配置。
定义激活的环境取值于 Maven
spring:
profiles:
active: @profile.active@
profile.active实际上就是一个变量,在maven打包的时候指定的-P prod 传入的就是值。
activeByDefault 指定默认环境
<profiles>
<profile>
<!--不同环境的唯一id-->
<id>dev</id>
<activation>
<!--默认激活开发环境-->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!--profile.active对应application.yml中的@profile.active@-->
<profile.active>dev</profile.active>
</properties>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>prod</id>
<properties>
<profile.active>prod</profile.active>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.mjtt.Application</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<!--根据激活条件引入打包所需的配置和文件-->
<resource>
<directory>src/main/resources</directory>
<!--引入所需环境的配置文件-->
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<!--根据maven选择环境导入配置文件-->
<include>application-${profile.active}.yml</include>
<!--如果需要 resources 下的其他文件也要加入!比如 mapper.xml!-->
<include>**/*.xml</include>
<include>**/*.lua</include>
</includes>
</resource>
</resources>
</build>
IDEA 的 Maven 选项卡会出现:
可以选择打包的环境,然后点击package即可。
或者项目根目录用命令打包,不过需要使用-P 指定环境
mvn clean package package -P prod