Java - Build Run Maven Project Command Line

Java - Build Run Maven Project Command Line

ArcheType for simple Java Project

Setting up a maven project on your favorite IDE can be time consuming and slow. Many developers prefer to setup maven project from command line use their favorite text editor to write code. Maven is a build tool and setting up a boilerplate seed project shouldn't be an issue.


#generate simple java maven project
mvn archetype:generate -DgroupId=com.yourcompany -DartifactId=myproject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This will create a java project (not web) with package com.yourcompany and folder name as myproject. Skips the interactive steps. The generated maven project will include a basic structure for the java project along with test packages. You can later add the JUnit dependency for writing tests.

The package name of your project becomes the groupId and the name of the project is artifactId.

Compile the project

Maven comes with predefined goals.

The compile goal will

#compile the project and generate target folder
mvn compile

If changes are made to the code, mvn compile needs to be executed again before calling exec.


Running the maven project

Maven's exec plugin can be used to run any of the main class generated in the target folder. Here the main class being com.mycompany.App

#execute the project
mvn exec:java -Dexec.mainClass=com.mycompany.App

Note: You cannot execute the maven project with Exec plugin without the compile step. Since this step checks the target directory for the classes to call.

If you would like to pass parameters, you can use exec.args option as follows.

mvn exec:java -Dexec.mainClass=com.mycompany.App -Dexec.args="foo bar"

Running Unit Tests

If you want to run tests, run the test goal. It will run all the tests created using the surefire plugin.

mvn test

You can also run a single test file or a particular method inside a test file as follows.

mvn test -Dtest=com.mycompany.AppTest#testMethod

Misc

In case you want to move the project or upload it over ftp or somewhere. Before creating the zip of your code, call mvn clean to clean-up the target directly. Helps to keep the size low.:)

If you are pushing your code to a git repository, consider adding Maven .gitignore to it.

.gitignore

target/

This will exclude the target folder from the git repo.

If you are looking forward to generate webapp with maven, read Build and Deploy maven project with embedded tomcat.