Apache Maven, Java, Software Development

Create Java Project Using Maven in Command Line

This post shows how to create a Java project with Apache Maven in the command line. The content may be old, and a myriad of people may already know how this, but it is still worth learning the basics.

Requirements

We will use the following items.

  1. Apache Maven 3.6.3. Download and extract to a directory.
  2. OpenJDK 11. Download a zip distribution and extract it to another directory.
  3. Windows 10

Set Up Environment Variables

Before you move on, we need to set up some environment variables so that we can use Apache Maven with OpenJDK 11. On the command line window, run the following commands.

Then, change to a directory where we want to create a Java project using Apache Maven.

Create Java Project From Maven Archetype

Apache Maven archetypes are Java project templates from which we can choose. To create a Java project, we use the following one-line command.

Consider the following usage. Note that it is a single-line command.

Once we successfully created a Java project, change the directory to the com-turreta-mavenproj directory.

Directory Structure Created By Maven

When we create a Java project, we get the following directory structure and files – excluding the target directory. Maven creates that directory when it builds the whole project.

Other Apache Maven Commands For Our Java Project

Without using an IDE, there are many things we can do without Java project using Apache Maven commands. The following commands are the ones programmers commonly use.

To delete the target directory, use the following command.

Sample usage.

To compile our codes, run the following command.

When we run the command, we get the following output on the console.

To run all unit tests within our codes, use the following command.

We get the following output when we run the command.

When we want to package our codes as a jar file, we use the following command.

And we get the following output.

Notice that the package command does compilation and runs the tests.  In Apache Maven, there is the concept of the build lifecycle, and it has seven phases that we can use with our Java project.

  1. validate – validates the whole project
  2. compile – validates the entire project and compiles the codes
  3. test – performs the first two phases and run the unit tests
  4. package – it does the early three steps and packages the byte-code files in a jar file
  5. verify – it does the first four phases and run integration tests if there are any
  6. install – does the early five phases and install the jar file into the local repository
  7. deploy – same as install but deploys the jar file to a remote repository

This post is part of a reboot Java tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like