Maven Profile 的應用

maven 的 profile 應用 或多或少都會出如今中大型的公司中。spring

若是你是第一次接觸maven 這個profile, 可能你並不會關心它到底是作什麼用的,就像我同樣。微信

即便見過不少次,可是不須要本身配置,能動就好。app

可是問題出現以後,你就可能發現不了什麼問題了。maven

基本概念

Profile ,跟基本翻譯出來的意思差很少,在技術翻譯中就是配置的意思。根據不一樣的profile,運行時替換掉定義好的變量值。學習

若是你用過spring的profile,大概就知道怎麼樣了。ui

不一樣類型的profile

  • 項目級別的profile

定義POM文件中spa

  • 用戶級別

定義在 (%USER_HOME%/.m2/settings.xml)翻譯

  • 全局 定義在 (${maven.home}/conf/settings.xml).

如何激活profile?

  • Explicitly
  • Through Maven settings
  • Based on environment variables
  • OS settings
  • Present or missing files
在 setting 配置文件中,顯式啓動

在配置文件中,能夠在<activeProfiles> 標籤內,顯式指定要啓動的profilecode

以下:server

<settings>
  ...
  <activeProfiles>
    <activeProfile>profile-1</activeProfile>
  </activeProfiles>
  ...
</settings>
基於build的環境變量來啓動

下面的配置表明,當jdk 版本號在 1.3 到 1.5之間的狀況下,profile就會被激活

<profiles>
  <profile>
    <activation>
      <jdk>[1.3,1.6)</jdk>
    </activation>
    ...
  </profile>
</profiles>

下面這個則是,基於運行時的變量來指定,若是 系統變量中有「environment」 且 值爲 "test"的時候,下面的profile就或被激活。

mvn groupId:artifactId:goal -Denvironment=test

<profiles>
  <profile>
    <activation>
      <property>
        <name>environment</name>
        <value>test</value>
      </property>
    </activation>
    ...
  </profile>
</profiles>
具體應用

那麼實際中,能夠利用profile來作什麼東西?

一般在pom層面的profile的靈活性會高不少,由於這只是針對項目級別,修改profile的配置不會影響到其餘的項目。

具體能夠在pom中修改的內容項有以下:

<repositories>
<pluginRepositories>
<dependencies>
<plugins>
<properties> (not actually available in the main POM, but used behind the scenes)
<modules>
<reporting>
<dependencyManagement>
<distributionManagement>
a subset of the <build> element, which consists of:
<defaultGoal>
<resources>
<testResources>
<finalName>

這些都是能夠被profile中定義的屬性替換掉pom中的值。

具體例子

下面這個配置指定了一個appserver.home

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.myco.plugins</groupId>
        <artifactId>spiffy-integrationTest-plugin</artifactId>
        <version>1.0</version>
        <configuration>
          <appserverHome>${appserver.home}</appserverHome>
        </configuration>
      </plugin>
      ...
    </plugins>
  </build>
  ...
</project>

咱們在POM中再加上以下的profile配置

<project>
  ...
  <profiles>
    <profile>
      <id>appserverConfig-dev</id>
      <activation>
        <property>
          <name>env</name>
          <value>dev</value>
        </property>
      </activation>
      <properties>
        <appserver.home>/path/to/dev/appserver</appserver.home>
      </properties>
    </profile>
 
    <profile>
      <id>appserverConfig-dev-2</id>
      <activation>
        <property>
          <name>env</name>
          <value>dev-2</value>
        </property>
      </activation>
      <properties>
        <appserver.home>/path/to/another/dev/appserver2</appserver.home>
      </properties>
    </profile>
  </profiles>
  ..
</project>

這個profile的配置被激活時,能夠替換掉定義的變量值。

按照這個方法,其餘的配置也能夠相應的進行配置改變。

掃描二維碼,進技術羣一塊兒學習成長:

微信profile.png

相關文章
相關標籤/搜索