从maven传递一个java参数 [英] pass a java parameter from maven
问题描述
我需要用maven执行一些测试,并从命令行传递一个参数。
I need to execute some tests with maven, and pass a parameter from the command line.
我的java代码应该得到如下参数:
System .getenv(my_parameter1);
My java code should get the parameter as: System.getenv("my_parameter1");
我在pom.xml文件中定义参数如下例所示:
(后者,我是修改pom.xml以从公共行获取参数mvn clean install -Dmy_parameter1 = value1)
and I define the parameter in the pom.xml file as the example below: (and latter, I'd modify the pom.xml to get the parameter from the common line mvn clean install -Dmy_parameter1=value1)
但它不起作用; System.getenv(my_parameter1)返回null。
我应该如何在pom.xml文件中定义参数?
but it does not work; System.getenv("my_parameter1") returns null. how should I define the parameter in the pom.xml file?
pom.xml
<project>
...
<profiles>
<profile>
<properties>
<my_parameter1>value1</my_parameter1>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>slowTest</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skip>false</skip>
<includes>
<include>**/*Test.java</include>
<include>**/*TestSlow.java</include>
</includes>
<properties>
<my_parameter1>value1</my_parameter1>
</properties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
推荐答案
System.getenv ()读取环境变量 ,例如 PATH
。您想要的是读取系统属性。 -D [系统属性名称] = [value]用于系统属性,而不是环境变量。
System.getenv() reads environment variables, such as PATH
. What you want is to read a system property instead. The -D[system property name]=[value] is for system properties, not environment variables.
您有两种选择:
-
如果要使用环境变量,请使用特定于操作系统的方法设置环境变量
my_parameter1
你推出了Maven。在Windows中,使用set my_parameter1 =< value>
,在'nix useexport my_parameter1 =< value>
中。
If you want to use environment variables, use the OS-specific method of setting the environment variable
my_parameter1
before you launch Maven. In Windows, useset my_parameter1=<value>
, in 'nix useexport my_parameter1=<value>
.
您可以使用 System.getProperty()从代码中读取系统属性值。
You can use System.getProperty() to read the system property value from within your code.
示例:
String param = System.getProperty("my_parameter1");
在您的surefire插件配置中,您可以使用:
In you surefire plugin configuration, you can use:
<configuration>
<systemPropertyVariables>
<my_property1>${my_property1}</my_property1>
</systemPropertyVariables>
</configuration>
Maven属性_my_property1_并在测试中设置它。
Which takes the Maven property _my_property1_ and sets it also in your tests.
有关此此处的详细信息。
我不确定Maven的系统属性是否会自动传递给测试和/或fork模式是否影响是否会发生这种情况,因此传递它们可能是个好主意明确地说。
I'm not sure if system properties from Maven are automatically passed to tests and/or whether fork mode affects whether this happens, so it's probably a good idea to pass them in explicitly.
这篇关于从maven传递一个java参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!