Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variable with Maven

I've ported a project from Eclipse to Maven and I need to set an environment variable to make my project work.

In Eclipse, I go to "Run -> Run configurations" and, under the tab "environment", I set "WSNSHELL_HOME" to the value "conf".

How can I do this with Maven?

like image 959
Gianluca Avatar asked Apr 01 '11 08:04

Gianluca


People also ask

How do I set environment variables in Maven?

Step 5 - Set Maven Environment VariablesAdd M2_HOME, M2, MAVEN_OPTS to environment variables. Set the environment variables using system properties. Open command terminal and set environment variables. Open command terminal and set environment variables.

How do I set an environment variable in Maven POM?

To refer to environment variables from the pom. xml, we can use the ${env. VARIABLE_NAME} syntax. We should remember to pass the Java version information via environment variables.

Can I use Maven without setting the environment variable?

Yes it does not depend on your OS.


2 Answers

You can just pass it on the command line, as

mvn -DmyVariable=someValue install 

[Update] Note that the order of parameters is significant - you need to specify any options before the command(s).[/Update]

Within the POM file, you may refer to system variables (specified on the command line, or in the pom) as ${myVariable}, and environment variables as ${env.myVariable}. (Thanks to commenters for the correction.)

Update2

OK, so you want to pass your system variable to your tests. If - as I assume - you use the Surefire plugin for testing, the best is to specify the needed system variable(s) within the pom, in your plugins section, e.g.

<build>     <plugins>         ...         <plugin>             <groupId>org.apache.maven.plugins</groupId>             <artifactId>maven-surefire-plugin</artifactId>             ...             <configuration>                 ...                 <systemPropertyVariables>                     <WSNSHELL_HOME>conf</WSNSHELL_HOME>                 </systemPropertyVariables>             </configuration>         </plugin>         ...     </plugins> </build> 
like image 173
Péter Török Avatar answered Sep 20 '22 07:09

Péter Török


The -D properties will not be reliable propagated from the surefire-pluging to your test (I do not know why it works with eclipse). When using maven on the command line use the argLine property to wrap your property. This will pass them to your test

mvn -DargLine="-DWSNSHELL_HOME=conf" test 

Use System.getProperty to read the value in your code. Have a look to this post about the difference of System.getenv and Sytem.getProperty.

like image 34
FrVaBe Avatar answered Sep 22 '22 07:09

FrVaBe