Tim
Tim

Reputation: 99576

How can I run a program compiled by Maven?

I am starting to learn Maven by reading https://spring.io/guides/gs/maven/.

In the examples, after running mvn compile successfully, how can I run the program via maven? This part seems missing from the article.

Thanks.

Upvotes: 3

Views: 4542

Answers (3)

Eugene S
Eugene S

Reputation: 6910

Generally, maven is not used for running code. This is a build tool that you can use for compiling, running unit or integration tests, deploying you your code locally and remotely, etc..

It is based around the idea of a build lifecycle where which is in its turn is defined by a list of build phases. For example, the default lifecycle has the following phases:

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

For more information you can refer to this.

UPDATE:

Having said that, it is possible as mentioned in Thorbjørn Ravn Andersen answer here.

Upvotes: 1

You can invoke a Java program (i.e. with a public static void main(String[] args) signature) with the classpath of the combined dependencies for the current pom.xml using

mvn -q exec:java

You need to configure the main class to invoke in your pom.xml similar to

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>demo.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

This is useful for testing and development, but not deployment

See http://www.mojohaus.org/exec-maven-plugin/usage.html for full details.

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522751

The Maven build process has a number of lifecycles, or points in the process. compile is one of the build steps, but most likely running the following would resolve your issue:

mvn clean package

This would generate a JAR file, in the folder where you ran it. You can then try running this JAR file using java.

Upvotes: 1

Related Questions