用maven的profile控制不同环境下的配置项目

本文介绍如何利用Maven Profile技术在不同的操作系统和环境中灵活管理配置项,通过配置文件区分和mvn命令参数实现开发、测试、预发布、生成等不同环境的配置切换。

在项目开发过程中,我们经常遇到这样的问题,就是我们的配置项会因为环境的不同,配置项文件的内容也不同。

举个简单的例子吧。

数据库的连接,我们在不同的环境下,使用的数据库一般都是不同的,开发环境使用开发数据库,测试环境使用测试数据库,线上环境使用生产数据库。

(感叹下:淘宝数据库使用的是TDDL动态数据源,并且有SCM配置中心进行配置项的管理,所以开发者无需关心这类问题)

那么,在没有配置中心的情况下,我们怎么管理我们的配置项呢?

其实,maven已经提供了这方面的,支持。这个就是profile。你可以按照如下方式配置你的pom文件,可以做到简单的配置文件区分。(假设开发者机器是windows,使用的配置项文件是dev.properties,生产机使用的是linux,使用的配置项文件是pro.properties)

POM部分配置内容:

<profiles>

        <profile>

            <id>linux</id>

            <activation>

                <os>

                    <family>linux</family>

                </os>

            </activation>

            <properties>

                <antx.properties.file>

                     ${basedir}/src/main/webapp/META-INF/pro.properties

                </antx.properties.file>

            </properties>

        </profile>

        <profile>

            <id>windows</id>

            <activation>

                <os>

                    <family>windows</family>

                </os>

            </activation>

            <properties>

                <antx.properties.file>

                     {basedir}/src/main/webapp/META-INF/dev.properties

                 </antx.properties.file>

            </properties>

        </profile>

    </profiles>

 

这是最简单的处理方式,根据操作系统不同来选择不同的文件作为你的配置项。

但如果你的环境还分开发环境(dev)、测试环境(test)、预发布环境(rea)、生成环境(pro)呢,仅仅靠操作系统是无法区分开的。

 

这时候   mvn package –P  ${profileId}   可以帮到你。

 

POM文件配置如下:

 

<build>部分:

 

<build>

        .....此次省略部分配置内容...

        <filters>

            <filter>{basedir}/src/main/webapp/META-INF/{env}.properties </filter>

        </filters>

        .....此次省略部分配置内容...

</build>

 

     <profiles>部分:

 

  <profiles>

       <!-- 开发环境,默认激活 -->

       <profile>

           <id>dev</id>

           <properties>

              <env>dev</env>

           </properties>

           <activation>

              <activeByDefault>true</activeByDefault><!--默认启用的是dev环境配置-->

           </activation>

       </profile>

       <!-- 测试环境 -->

       <profile>

           <id>test</id>

           <properties>

              <env>test</env>

           </properties>

       </profile>

       <!-- 预发布环境 -->

       <profile>

           <id>rea</id>

           <properties>

              <env>rea</env>

           </properties>

       </profile>

       <!-- 生产环境 -->

       <profile>

           <id>pro</id>

           <properties>

              <env>pro</env>

           </properties>

       </profile>

  </profiles>

 

这样,当执行  mvn package –P  test 将会使用test.properties作为你的配置项文件,

执行mvn package –P  pro 将会使用pro.properties作为你的配置项文件。

是不是灵活多啦?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值