Profile能让你为一个特殊的环境自定义一个特殊的构建;profile使得不同环境间构建的可移植性成为可能。Maven中的profile是一组可选的配置,可以用来设置或者覆盖配置默认值。有了profile,你就可以为不同的环境定制构建。profile可以在pom.xml中配置,并给定一个id。然后你就可以在运行Maven的时候使用的命令行标记告诉Maven运行特定profile中的目标。一个Profiles下面允许出现的元素:
<project>
<profiles>
<profile>
<build>
<defaultGoal>...</defaultGoal>
<finalName>...</finalName>
<resources>...</resources>
<testResources>...</testResources>
<plugins>...</plugins>
</build>
<reporting>...</reporting>
<modules>...</modules>
<dependencies>...</dependencies>
<dependencyManagement>...</dependencyManagement>
<distributionManagement>...</distributionManagement>
<repositories>...</repositories>
<pluginRepositories>...</pluginRepositories>
<properties>...</properties>
</profile>
</profiles>
</project>
profile的激活方式
Maven提供了多种不同的profile激活方式。比如可以使用mvn命令的-P参数显示的激活一个profile,也可以根据环境条件的设置让它自动激活等。
使用activeByDefault设置激活
<profiles>
<profile>
<id>gray</id>
<properties>
<cn.springcloud.gray.version>A.1.1.0.RELEASE</cn.springcloud.gray.version>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
在settings.xml中使用activeProfiles指定处于激活状态的profile
在settings.xml中使用activeProfiles来指定需要激活的profile,这种方式激活的profile将所有情况下都处于激活状态
<profiles>
<profile>
<id>gray</id>
<properties>
<cn.springcloud.gray.version>A.1.1.0.RELEASE</cn.springcloud.gray.version>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>profileTest1</activeProfile>
</activeProfiles>
使用-P参数显示的激活
在进行Maven操作时就可以使用-P参数显示的指定当前激活的profile。可以指定多个profile,profile之间用逗号隔开
mvn clean install -Pgray
mvn clean install -P gray
mvn clean install -Pgray,test
使用-P参数显示的不激活
当项目使用activeByDefault或settings.xml中激活的profile,但是在某些场景下又不想它处于激活状态。比如不想做让gray处于激活状态,这个时候可以这样做
mvn clean install -P !gray
查看当前处于激活状态的profile
Maven提供了一个指令可以查看当前处于激活状态的profile,查看命令是
mvn help:active-profiles
不同环境依赖不同的版本或jar包、插件
在项目的开发过程中,可能会有这样的需求,生产环境依赖的jar包必须是release版本, 测试环境可以是snapshot版本。这个时候就可以使用profile去管理不同环境的依赖。如下:
<project ... >
<properties>
<springcloud-gray.version>1.0.0.RELEASE</springcloud-gray.version>
</properties>
<dependencies>
<dependency>
<groupId>cn.springcloud.gray</groupId>
<artifactId>spring-cloud-starter-gray-client</artifactId>
<version>${springcloud-gray.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>test</id>
<properties>
<zma-stu-springcloud-gray.version>1.1.0-SNAPSHOT</zma-stu-springcloud-gray.version>
</properties>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</profile>
</profiles>
</project>
idea上管理maven profiles
在idea上对maven的profiles进行管理是非常简单的。
在maven面板中,Maven -> Profiles