Wednesday, 15 July 2015

3 ways to run Java main from Maven

Overview

Maven exec plugin lets you run the main method of a Java class in your project, with the project dependencies automatically included in the classpath. This article show you 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

Since you are not running your code in a maven phase, you first need to compile the code. Remember exec:java does not automatically compile your code, you need to do that first.

mvn compile  

Once your code is compiled, the following command runs your class

Without arguments:
mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  

With arguments:
mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"

With runtime dependencies in the CLASSPATH:
mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

<build>
 <plugins>
  <plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>exec-maven-plugin</artifactId>
   <version>1.1.1</version>
   <executions>
    <execution>
     <phase>test</phase>
     <goals>
      <goal>java</goal>
     </goals>
     <configuration>
      <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>
      <arguments>
       <argument>arg0</argument>
       <argument>arg1</argument>
      </arguments>
     </configuration>
    </execution>
   </executions>
  </plugin>
 </plugins>
</build>
To run the exec plugin with above configuration, simply run the corresponding phase.

mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

<profiles>
 <profile>
  <id>code-generator</id>
  <build>
   <plugins>
    <plugin>
     <groupId>org.codehaus.mojo</groupId>
     <artifactId>exec-maven-plugin</artifactId>
     <version>1.1.1</version>
     <executions>
      <execution>
       <phase>test</phase>
       <goals>
        <goal>java</goal>
       </goals>
       <configuration>
        <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>
        <arguments>
         <argument>arg0</argument>
         <argument>arg1</argument>
        </arguments>
       </configuration>
      </execution>
     </executions>
    </plugin>
   </plugins>
  </build>
 </profile>
</profiles>
To call the above profile, run the following command:

mvn test -Pcode-generator  

Advanced options:
You can get a list of all available parameters by typing:
mvn exec:help -Ddetail=true -Dgoal=java  

No comments:

Post a Comment