Maven profiles

Maven 中的 profiles,大致上可以想象成 Spring 中的 profile,都是用来管理不同环境下的配置。

概述

举一个简单的例子,我们有开发环境和测试环境,开发环境用的内存型数据库,测试环境用的测试用的 MySQL 数据库,数据库连接信息写在了 db.properties 文件中,如果每次构建都要手动修改连接信息肯定是很不方便的,这时候 profiles 就很有用了。

比如我们的配置文件 db.properties 如下

db.url = ${db.url}
db.username = ${db.username}

我们需要在 Maven 构建的时候根据激活的 profile 来替换这些值,在 pom.xml 中有如下配置:

   <profiles>
       <profile>
           <id>dev</id>
           <activation>
               <activeByDefault>true</activeByDefault>
           </activation>
           <properties>
               <db.url>dev://embed:3306</db.url>
               <db.username>dev-root</db.username>
           </properties>
       </profile>

       <profile>
           <id>test</id>
           <properties>
               <db.url>jdbc:mysql://localhost:3306/test</db.url>
               <db.username>test-root</db.username>
           </properties>
       </profile>
   </profiles>

可以看到我们配置了两个 profiles,id 是他们的标识,这两个配置有不同的 properties,那么当我们进行构建的时候,对资源文件进行 filtering 的时候就能根据不同的配置使用不同的 properties 了。使用 -P 选项来指定使用的 profile。如 mvn package -P test ,也可以指定多个 profile,使用 , 分隔。

Profiles 的作用范围

profiles 的作用范围可分为四种:

  • 项目级:定义在项目中的 pom.xml
  • 用户级:定义在用户的 Maven-setting 中 (%USER_HOME%/.m2/settings.xml)
  • 全局:定义在 Maven 全局配置文件中 (${maven.home}/conf/settings.xml)

通常我们会将 profiles 配置在每个项目中,方便团队合作。

POM 中 profiles 可配置元素

  • <repositories>
  • <pluginRepositories>
  • <dependencies>
  • <plugins>
  • <properties>
  • <modules>
  • <reporting>
  • <dependencyManagement>
  • <distributionManagement>
  • <build> 元素的部分子元素,包括
    • <defaultGoal>
    • <resources>
    • <testResources>
    • <finalName>

profile 的激活

激活 profile 有以下几种方式:

  • 显示指定
  • 通过 Maven settings
  • 基于环境变量
  • 系统设置
  • 特定文件的存在与否

通常我们使用显示指定的方式。

显示指定,就是在命令行中使用 -P 选项。

mvn groupId:artifactId:goal -P profile-1,profile-2

这个选项可传入逗号分隔的 profile 的 id,使用这个选项会激活传入的 profiles,此外还包括在 settings.xml 中配置了 activeProfiles 的 profiles。

<settings>
  ...
  <activeProfiles>
    <activeProfile>profile-1</activeProfile>
  </activeProfiles>
  ...
</settings>

<activeProfiles> 标签中列出的 profiles 默认会被激活。

通常我们还会指定一个默认激活的 profiles,比如上面的例子中,通过设置 <activeByDefault> 为 true 来使某个 profile 默认激活。

如何查看当前激活的 profiles

使用命令行

mvn help:active-profiles

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值