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

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

举个简单的例子吧。

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

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

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

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

POM部分配置内容:

<profiles>

        <profile>

            <id>linux</id>

            <activation>

扫描二维码关注公众号,回复: 650525 查看本文章

                <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作为你的配置项文件。

是不是灵活多啦?

猜你喜欢

转载自javis163.iteye.com/blog/1727578