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
Maven Build command
Maven comes with predefined goals.
The compile goal will
- download all the dependencies
- compile the project
- and generate the target folder.
#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.
The following command builds the maven project and installs it into local maven repository.
Before that if you wish to clean the
target/ folder. Run the following maven build command
mvn clean install
If you are looking to package the project, then you should run
Maven Skip Test Command
If you are executing any of the above build or package maven goals, you may want to skip tests. JUnit tests written in your maven project can be skipped by adding the
mvn -Dmaven.test.skip=true package
Maven Run Command
Maven's exec plugin can be used to run any of the main class generated in the target folder.
Here the main class being
#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.
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
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.
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.