1. Overview

In this short tutorial, we’re going to see how to run arbitrary main methods from any Java class using Maven.

2. The exec-maven-plugin

Let’s suppose we have the following class:

public class Exec {     private static final Logger LOGGER = LoggerFactory.getLogger(Exec.class);     public static void main(String[] args) {        LOGGER.info("Running the main method");        if (args.length > 0) {            LOGGER.info("List of arguments: {}", Arrays.toString(args));        }    }}

And we want to execute its main method from the command line via Maven.

In order to do this, we can use the exec-maven-plugin. To be more specific, the _exec:java _goal** from this plugin executes the supplied Java class with the enclosing project’s dependencies as the classpath.**

To execute the main method of the Exec class, we have to pass the fully qualified name of the class to the plugin:

$ mvn compile exec:java -Dexec.mainClass="com.baeldung.main.Exec"02:26:45.112 INFO com.baeldung.main.Exec - Running the main method

As shown above, we’re using the _exec.mainClass _system property to pass the fully qualified class name.

Also, we have to make sure that the classpath is ready before running the main method. That’s why we’re compiling the source code before executing the main method.

We can achieve the same thing with plain _java _and _javac. _However, this can be cumbersome when we’re working with a pretty large classpath. On the contrary,when using this plugin, Maven automatically takes care of populating the classpath.

#java #maven

Run a Java Main Method in Maven
9.50 GEEK