Maven-build结合profile实现多环境配置实战

问题

开发一个项目,主要有开发、测试和最终部署上线几个阶段,每个阶段对配置(数据库、日志)都有不同的设置。每次上线都由部署工程师负责修改配置并上线。这样的工作方式导致每次上线时大家都心惊胆颤,决定研究下maven如何解决这个问题。

思路

将几个环境的配置项分类,概括为数据库配置、log日志路径配置、外部依赖的接口配置。
如果能实现在生成不同的发布包时对资源进行不同的替换就可以达到目的了。而maven的build结合profile,即可动态指定配置文件来实现

步骤

1、首先需要在pom文件中确定filter和要filter的资源,这是通过在build节点中添加filter和resource来实现的。
2、然后pom文件配置profile的多个id,通过mvn package -P,动态指定配置。

示例

build标签:

<build>
    <filters>
        <filter>src/main/filters/filter-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

build/resource/directory配置表示要对src/main/resources下的资源进行过滤;build/resource/filtering配置表示过滤方式采用文件过滤。
build/filter表示过滤文件为src/main/filters/filter-${env}.properties,其中${env}是一个变量,通过在pom文件中通过profile定义。

profiles标签:

<!--此处可以配置默认激活-->
<properties>
    <env>dev</env>
</properties>

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <env>dev</env>
        </properties>
        <activation>
            <!--这个字段表示默认激活-->
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile> 
    <profile> 
        <id>test</id>
        <properties>
            <env>test</env>
        </properties>
    </profile>
    <profile>
        <id>product</id>
        <properties>
            <env>product</env>
        </properties>
    </profile>
</profiles>

properties/env配置${env}的默认值。
profiles配置不同环境的配置。profile/id配置id,profile/properties/env配置${env}。
通过mvn package -P(id),动态指定配置${env}。例如:maven package -Pproduct,则会使用 filter-product.properties中的内容来替换resources目录中的配置文件,比如我们项目resources下有db.properties。

db.properties文件内容如下:

...
jdbc.connection.url=${ymqx.jdbc.url} 
jdbc.connection.username=${ymqx.jdbc.username} 
jdbc.connection.password=${ymqx.jdbc.password}
...

filter-product.properties文件内容如下:

...
ymqx.jdbc.url=jdbc:mysql://localhost:3306/ymqx?characterEncoding=UTF-8
ymqx.jdbc.username=root
ymqx.jdbc.password=admin
...

maven执行命令 maven package -Pproduct 后,db.properties的内容:

...
jdbc.connection.url=jdbc:mysql://localhost:3306/ymqx?characterEncoding=UTF-8
jdbc.connection.username=root
jdbc.connection.password=admin
...

小结

build结合profile实现多环境动态配置完成。build指定资源文件目录;profile配置多环境的配置id;通过maven package -P,指定id动态加载资源文件。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会叫的狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值