StackTips

Creating Maven Java Project using CommandLine

Here are the steps to create your first Maven Java project using the command line:

  1. Install Maven: Make sure Maven is installed on your system. You can check if Maven is installed by running the command mvn -version in the terminal. If Maven is not installed, you can download it from the official Maven website and follow the installation instructions.
  1. Create a new project directory: Create a new directory for your project. For example, you can create a directory called "my-maven-project".
mkdir my-maven-project
  1. Navigate to the project directory: Navigate to the newly created directory.
cd my-maven-project
  1. Create a new Maven project: Create a new Maven project using the mvn archetype:generate command. This command generates a new Maven project based on a template or archetype.
mvn archetype:generate 
    -DgroupId=com.example.app 
    -DartifactId=my-app 
    -DarchetypeArtifactId=maven-archetype-quickstart 
    -DinteractiveMode=false

By the way, you don’t have to remember each of these parameters provided above. Just use the interactiveMode=true, so that Maven asks for all the required parameters.

In this command, the groupId and artifactId are the unique identifiers for your project. The archetypeArtifactId specifies the archetype to use, which in this case is the maven-archetype-quickstart archetype, which creates a simple Java project with a main class.

  1. Build the project: Navigate to the project directory and build the project using the mvn package command. This will compile the project, run the tests, and package the project into a JAR file.
> cd my-app
> mvn package
  1. Run the project: You can run the project using the java -cp target/my-app-1.0-SNAPSHOT.jar com.example.app.App command. This will execute the main method in the App class.
java -cp target/my-app-1.0-SNAPSHOT.jar com.example.app.App

Congratulations, you have created and built your first Maven Java project using the command line!