Maven 利用 profile 进行多环境配置

我们在进行项目的多环境配置时,有很多种方式供我们选择,比如 SpringBoot 自带的 application-dev.yml、maven 的 profile 等。这里介绍的就是如何利用 profile 进行多环境配置。

首先,在 pom.xml 中添加你需要的 profile 配置:

    <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 是默认激活状态。

接下来,我们要将 resource 的 filtering 标签设置为 true,表示启用参数化值来替换标记,而参数化值源于 filter 标签中的 properties 文件。以下是原文解释:

 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 文件中配置了不同环境的值:

前面说到 <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} 这些。

最后,只剩下一个问题了,怎么切换环境呢?如果你开发的工具是 IDEA,直接在旁边窗口切换即可:

如果使用命令行编译,加上 -P 选择 profile 即可,如下:

clean -U package -P dev -DskipTests=true -f pom.xml

猜你喜欢

转载自www.cnblogs.com/jmcui/p/11925020.html