maven工程的多环境配置方案(profile)

 

前言:
  写一篇水文来打发下时间吧^_^. 在应用开发中, 总会遇到开发/测试/预发布/线上环境, 其环境不同, 其具体的配置项也有所不同, 因此如何快速的切换各个环境配置, 进行打包配置, 成了一个小痛点.
  本文主要讲述基于maven构建的java工程(基于spring), 如何实现多环境配置, step by step.

 

多环境配置:
  把多环境的配置文件集中起来, 比如按如下方式整合于工程代码.
  
  需要被打包替换的配置文件app.properties文件存于src/main/resource/conf下, 其内容为:

1
2
key.name=${key.name}
key.value=${key.value}

 

profile标签:
  在maven中profile标签就是为多环境配置而生, 它支持定义了各个环境下的变量集, 选取激活某个profile后, 会自动屏蔽掉其他profile的变量.
  比如定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<profiles>
    <profile>
        <id>test</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>test</env>
        </properties>
    </profile>
    <profile>
        <id>online</id>
        <properties>
            <env>online</env>
        </properties>
    </profile>
</profiles>

  这边定义了test, online两个profile.
  
  此时默认打包, 其会选用test这个profile, 原因是因为它是默认激活的, 也就是说变量env(key=env, value=test)将作用于pom.xml文件的其他配置项.

 

filter&resource标签:
  filter和resource标签是一块使用的, 前者指定了载入的properties文件, 后者则指定了key/value对替换的目标作用目录.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<build> 
    <finalName>test-app-project</finalName>
     
    <!-- 使用指定的filter进行过滤,在执行mvn命令的时候带上-Ptest就代表测试环境(默认),
        就会加载测试环境的properties,-Ponline就代表线上环境 -->
    <filters>
        <filter>settings/${env}/app.properties</filter>
    </filters>
 
    <!-- 资源文件位置src/main/resources/,
        这下面的资源文件的${}会全部被替换成filter中的标签内容 -->
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <!-- exclude可以排除指定文件,支持通配符, 匹配项不会生成到classes目录下 -->
            <!--<excludes>-->
            <!--<exclude>env/dev.properties</exclude>-->
            <!--</excludes>-->
        </resource>
    </resources>
</build>

  其实从xml的配置中, 我们可以解读如下, filter目录为: settings/${env}/app.properties. 由于激活的profile为test, 则env为test. 这样filter目录为settings/test/app.properties. maven自动提取这个key/value文件, 把src/main/resource目录下的配置文件中${}全部替换.

 

测试:
  通过maven进行编译打包, 其可以指定命令行参数P, 指定激活那个profile.
  比如要激活online(线上配置), 则执行如下命令:

mvn -Ponline package

  执行之后具体的产出结果如下:
  

 

总结:
  maven的多环境配置, 算是一个基础的点. 这边纯粹写个水文吧, 记录一下^_^.

 

posted on   mumuxinfei  阅读(840)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2014-04-25 hive-jdbc/odbc的解读和看法

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示