1. Overview
1.概述
In this quick tutorial, we’re going to see how to read environment variables from Maven‘s pom.xml to customize the build process.
在这个快速教程中,我们将了解如何从Maven的pom.xml中读取环境变量来定制构建过程。
2. Environment Variables
2.环境变量
To refer to environment variables from the pom.xml, we can use the ${env.VARIABLE_NAME} syntax.
为了从pom.xml中引用环境变量,我们可以使用${env.VARIABLE_NAME}。语法。
For instance, let’s use it to externalize the Java version in the build process:
例如,让我们在构建过程中用它来外化Java版本。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${env.JAVA_VERSION}</source>
<target>${env.JAVA_VERSION}</target>
</configuration>
</plugin>
</plugins>
</build>
We should remember to pass the Java version information via environment variables. If we fail to do so, then we won’t be able to build the project.
我们应该记得通过环境变量传递Java版本信息。如果我们没有这样做,那么我们将无法构建该项目。
To run the Maven goals or phases against such a build file, we should first export the environment variable. For instance:
要针对这样的构建文件运行Maven目标或阶段,我们应首先导出环境变量。比如说。
$ export JAVA_VERSION=9
$ mvn clean package
On Windows, we should use “set VAR=value” syntax to export the environment variable.
在Windows上,我们应该使用“set VAR=value” 语法来导出环境变量。
In order to provide a default when the JAVA_VERSION environment variable is missing we can use a Maven profile:
为了在JAVA_VERSION环境变量缺失时提供一个默认值,我们可以使用Maven配置文件。
<profiles>
<profile>
<id>default-java</id>
<activation>
<property>
<name>!env.JAVA_VERSION</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
As shown above, we’re creating a profile and making it active only if the JAVA_VERSION environment variable is missing — !env.JAVA_VERSION part. If that happens, then this new plugin definition will override the existing one.
如上所示,我们正在创建一个配置文件,并且只有在JAVA_VERSION环境变量缺失的情况下才会使其激活 – !env.JAVA_VERSION部分。如果发生这种情况,那么这个新的插件定义将覆盖现有的插件。
3. Conclusion
3.总结
In this short tutorial, we saw how to customize the build process by passing environment variables to the pom.xml.
在这个简短的教程中,我们看到如何通过向pom.xml传递环境变量来定制构建过程。