Java 如何将 Jenkins 环境变量注入 Maven 构建?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21187934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject Jenkins environment variable into maven build?
提问by Atanas Kanchev
I need to get some of the Jenkins environment variables like BUILD_NUMBER and BUILD_URL and to inject them as variables in my Maven Java build.
我需要获取一些 Jenkins 环境变量,如 BUILD_NUMBER 和 BUILD_URL,并将它们作为变量注入到我的 Maven Java 构建中。
I have added this to the pom.xml
我已将此添加到 pom.xml
<properties>
<jenkins.buildUrl>${env.BUILD_URL}</jenkins.buildUrl>
</properties>
and while building with just mvn install I'm trying to get the variable by
在仅使用 mvn install 构建时,我试图通过
private static final String JENKINS_BUILD_URL = System.getProperty("jenkins.buildUrl");
but unfortunately the result is null...
但不幸的是结果为空...
What I'm doing wrong guys?
伙计们,我做错了什么?
采纳答案by Aurélien Thieriot
Guessing you are trying to read this value into your unit tests? Then you would have to configure the environment variables of the surefire plugin:
猜猜您正在尝试将此值读入您的单元测试?然后你必须配置surefire插件的环境变量:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<environmentVariables>
<jenkins.buildUrl>${env.BUILD_URL}</jenkins.buildUrl>
</environmentVariables>
</configuration>
</plugin>
As stated in this documentation: http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables
如本文档所述:http: //maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables
Note that it's possible to do the same in other plugin, like the Maven Tomcat Plugin for example.
请注意,可以在其他插件中执行相同的操作,例如 Maven Tomcat 插件。
回答by fjkjava
This how I achieved this in my application
这是我如何在我的应用程序中实现的
Add a property in pom.xml
在 pom.xml 中添加一个属性
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jenkins.buildNumber>${env.BUILD_NUMBER}</jenkins.buildNumber>
</properties>
Create a new property in .properties file
在 .properties 文件中创建一个新属性
jenkins.build.number = ${jenkins.buildNumber}
Enable filtering in maven by adding
通过添加在 Maven 中启用过滤
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
Then read it from java using the following code
然后使用以下代码从java中读取它
properties.load(MyClass.class.getResourceAsStream("/project.properties"));
version = properties.getProperty("jenkins.build.number");
Change the maven goal as clean package -Denv.BUILD_NUMBER=${BUILD_NUMBER}
将 maven 目标更改为干净的包 -Denv.BUILD_NUMBER=${BUILD_NUMBER}
I was displaying this in our application's about page.
我在我们的应用程序的关于页面中显示了这个。