Sunday, October 9, 2016

Passing Parameter In Maven

Maven also provide us the facility to pass parameter at runtime and we can use this property value from our Java code.

There  are several way to get properties value from maven. Here we will learn how to retrieve the System property value from maven.

We use "maven-surefire-plugin" to set System Property from pom.xml and then it is very easy to retrieve system property using java.

So our sample pom.xml is looks like below :

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<systemPropertyVariables>
<testproperty>tetsproppertyValue</testproperty>
</systemPropertyVariables>
</configuration>
</plugin>
Sample code example :
public class TestLocalRepoTest {

@Test
public void sampleTest(){
System.out.println("Test System Property Property Value From Maven :"+ System.getProperty("testproperty"));
}
}

if we want to run this main class from maven we need to type this command

test

We can also access the System Properties if we run the main java class from maven. Then we need to use "exec-maven-plugin" to set the System Propertiey

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${exec.mainClass}</mainClass>
<systemProperties>
<systemProperty>
<key>testproperty</key>
<value>tetsproppertyValue</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>

Sample code example :
public class TestLocalRepo {

public static void main(String[] args) {
System.out.println("Test System Property Property Value From Maven :" + System.getProperty("testproperty"));
}
}

if we want to run this main class from maven we need to type this command
exec:java  -Dexec.mainClass="com.automation.example.TestLocalRepo"