咱们在进行项目的多环境配置时,有不少种方式供咱们选择,好比 SpringBoot 自带的 application-dev.yml、maven 的 profile 等。这里介绍的就是如何利用 profile 进行多环境配置。redis
首先,在 pom.xml 中添加你须要的 profile 配置:spring
<profiles> <!-- 开发环境 默认激活--> <profile> <id>dev</id> <properties> <env>dev</env> </properties> </profile> <!-- 生产环境 --> <profile> <id>publish</id> <properties> <env>publish</env> </properties> </profile> <!-- 本地环境 --> <profile> <id>local</id> <properties> <env>local</env> </properties> <!--默认启用--> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> </profiles>
profiles 里面配置了多个 profile 文件,即 dev、publish、local 环境,<env> 标签是为了切换环境,激活不一样的环境须要。<activeByDefault> 设置为 true 代表:该 profile 是默认激活状态。tomcat
接下来,咱们要将 resource 的 filtering 标签设置为 true,表示启用参数化值来替换标记,而参数化值源于 filter 标签中的 properties 文件。如下是原文解释:app
Whether resources are filtered to replace tokens with parameterised values or not. The values are taken from the <code>properties</code> element and from the properties in the files listed in the <code>filters</code> element.
<build> <!-- 指定使用filter --> <filters> <filter>src/main/resources/profiles/${env}/env.properties</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/**</include> </includes> <excludes> <exclude>profiles/**</exclude> </excludes> <filtering>true</filtering> </resource> </resources> </build>
filter 中引用了 profile 的 env 属性,表示读取哪一个环境变量的值,不一样的 properties 文件中配置了不一样环境的值:
maven
前面说到 <filtering>true</filtering> 表示启用参数化值来替换标记,这是什么意思呢?咱们来看看 application.yml 中要怎么表示?工具
server: port: 8080 tomcat: max-threads: 800 uri-encoding: UTF-8 spring: redis: host: ${spring.redis.host} timeout: ${spring.redis.timeout} pool: max-idle: ${spring.redis.pool.max-idle} max-active: ${spring.redis.pool.max-active} password: ${spring.redis.password} database: ${spring.redis.database}
所以,整个流程应该是这样进行的:执行 maven compile 命令, <resource> 读取 <filter> 中 properties 的属性值,而后替换 src/main/resources 下中的标记 — 诸如 ${spring.redis.host} 这些。ui
最后,只剩下一个问题了,怎么切换环境呢?若是你开发的工具是 IDEA,直接在旁边窗口切换便可:
若是使用命令行编译,加上 -P 选择 profile 便可,以下:命令行
clean -U package -P dev -DskipTests=true -f pom.xml