Create a Maven Project in Java

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 259 of 306

There are two common ways to create a Maven project: generate it with the Maven Archetype plugin, or build the folders and pom.xml by hand. Both give you the standard layout that every Java IDE and CI server understands.

This lesson creates a project both ways, explains every generated file, sets the Java version and encoding, adds resource files, pins plugin versions, and splits a larger application into modules. It ends with a complete to-do command-line app built as an executable JAR. If pom.xml, phases and goals are new to you, read Maven in Java first.


Create a Maven Project With archetype:generate

An archetype is a project template. The maven-archetype-quickstart template creates a small Java application with one class and one test.

mvn archetype:generate \
  -DgroupId=com.gocourse.todo \
  -DartifactId=todo-cli \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.5 \
  -DinteractiveMode=false

On Windows Command Prompt, write the command on one line without the `` characters.

Output (shortened):

[INFO] Generating project in Batch mode
[INFO] Parameter: groupId, Value: com.gocourse.todo
[INFO] Parameter: artifactId, Value: todo-cli
[INFO] Parameter: package, Value: com.gocourse.todo
[INFO] Project created from Archetype in dir: /home/asha/todo-cli
[INFO] BUILD SUCCESS

The main generated files:

todo-cli/
├── pom.xml
└── src/
    ├── main/java/com/gocourse/todo/App.java
    └── test/java/com/gocourse/todo/AppTest.java

Build and run it:

cd todo-cli
mvn package
java -cp target/todo-cli-1.0-SNAPSHOT.jar com.gocourse.todo.App

Output:

Hello World!

How it works:

  • archetype:generate runs the generate goal of the Archetype plugin. -DinteractiveMode=false uses the values you passed instead of asking questions.
  • The package name defaults to the groupId, so App.java is in com.gocourse.todo.
  • The default version is 1.0-SNAPSHOT, which is why the JAR has that name.

Note: Templates are not updated often, so the generated pom.xml may use older Java and plugin versions. Check and update them using the sections below before you start coding. Run mvn archetype:generate without options to choose from a list of templates interactively.


Create a Maven Project by Hand

You do not need a template. A Maven project is just folders plus a pom.xml, so you can create it yourself in a few commands.

mkdir -p notes-app/src/main/java/com/gocourse/notes
mkdir -p notes-app/src/test/java/com/gocourse/notes
mkdir -p notes-app/src/main/resources
cd notes-app
<?xml version="1.0" encoding="UTF-8"?>
<!-- notes-app/pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.gocourse</groupId>
  <artifactId>notes-app</artifactId>
  <version>1.0.0-SNAPSHOT</version>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>
// src/main/java/com/gocourse/notes/NotesApp.java
package com.gocourse.notes;

public class NotesApp {
    public static void main(String[] args) {
        System.out.println("Notes app is ready. Java " + Runtime.version().feature());
    }
}
mvn -q compile
java -cp target/classes com.gocourse.notes.NotesApp

Output (the number is your JDK version):

Notes app is ready. Java 25

How it works:

  • mkdir -p creates the full folder path in one step. On Windows PowerShell, mkdir already creates missing parent folders.
  • The POM only has coordinates and two properties. Everything else, such as the source folder and output folder, comes from Maven's defaults.
  • -q hides Maven's log, so you only see errors. Runtime.version().feature() prints the major Java version that is running the program.

Files in a New Maven Project

File or folderPurpose
pom.xmlCoordinates, Java version, dependencies and plugins
src/main/javaApplication code; compiled into target/classes
src/main/resourcesNon-code files (properties, templates, SQL) copied into the JAR
src/test/javaTest code; compiled into target/test-classes, never packaged
src/test/resourcesFiles used only by tests
target/Build output; recreated on every build and ignored by Git
.mvn/ and mvnwOptional Maven Wrapper files that pin the Maven version

A minimal .gitignore for a Maven project:

target/
*.class
.idea/
*.iml
.vscode/

How it works:

  • Maven creates target/ on every build, so committing it only causes merge conflicts.
  • IDE folders are personal settings. The pom.xml alone is enough for any IDE to rebuild the project.

Note: To open a Maven project in IntelliJ IDEA, Eclipse or VS Code (with the Java extensions), open the folder that contains pom.xml. The IDE reads the POM, downloads dependencies and marks the source folders automatically.


Set the Java Version and Encoding in pom.xml

maven.compiler.release tells the compiler which Java version to target. It checks both the language features and the JDK APIs you use, so code that compiles is guaranteed to run on that version.

// src/main/java/com/gocourse/notes/Note.java
package com.gocourse.notes;

public record Note(String title, String body) {
}

With <maven.compiler.release>11</maven.compiler.release>, mvn compile fails:

[ERROR] COMPILATION ERROR :
[ERROR] /home/asha/notes-app/src/main/java/com/gocourse/notes/Note.java:[3,8] records are not supported in -source 11
  (use -source 16 or higher to enable records)
[INFO] BUILD FAILURE

With <maven.compiler.release>25</maven.compiler.release>, the same file compiles:

[INFO] Compiling 2 source files with javac [debug release 25] to target/classes
[INFO] BUILD SUCCESS

How it works:

  • Records arrived in Java 16, so a release of 11 rejects them. Raising the release to a version your team and servers run fixes the error.
  • The JDK that runs Maven must be at least the release version. JDK 25 can compile for release 11, but JDK 17 cannot compile for release 25.
  • project.build.sourceEncoding=UTF-8 makes the compiler and resource plugin read files as UTF-8 on every operating system, so characters such as ₹ are never corrupted.

Add Resources to a Maven Project

Files in src/main/resources end up on the classpath. Load them with getResourceAsStream, which works both from target/classes and from inside a JAR.

# src/main/resources/notes.properties
app.name=GOCOURSE Notes
notes.max=50
package com.gocourse.notes;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class NotesSettings {
    public static void main(String[] args) throws IOException {
        Properties settings = new Properties();
        try (InputStream in = NotesSettings.class.getResourceAsStream("/notes.properties")) {
            if (in == null) {
                throw new IllegalStateException("notes.properties not found on the classpath");
            }
            settings.load(in);
        }
        String appName = settings.getProperty("app.name");
        int maxNotes = Integer.parseInt(settings.getProperty("notes.max"));
        System.out.println(appName + " allows up to " + maxNotes + " notes");
    }
}
mvn -q compile
java -cp target/classes com.gocourse.notes.NotesSettings

Output:

GOCOURSE Notes allows up to 50 notes

How it works:

  • During process-resources, Maven copies notes.properties to target/classes/notes.properties.
  • The leading / in "/notes.properties" means "from the root of the classpath", not from the class's package folder.
  • Checking for null gives a clear error if the file is missing, instead of a confusing NullPointerException.

Pin Plugin Versions With pluginManagement

Maven uses default plugin versions that change between Maven releases. Pinning them in <pluginManagement> makes every developer and CI server build the project the same way.

<build>
  <pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>3.5.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.4.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.15.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.6</version>
      </plugin>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.5.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>3.1.4</version>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

After adding it, mvn clean package shows the pinned versions:

[INFO] --- clean:3.5.0:clean (default-clean) @ notes-app ---
[INFO] --- resources:3.4.0:resources (default-resources) @ notes-app ---
[INFO] --- compiler:3.15.0:compile (default-compile) @ notes-app ---
[INFO] --- surefire:3.5.6:test (default-test) @ notes-app ---
[INFO] --- jar:3.5.0:jar (default-jar) @ notes-app ---

How it works:

  • pluginManagement only sets versions and configuration. It does not add plugins to the build; the lifecycle still decides which ones run.
  • Plugins with the default group org.apache.maven.plugins can leave out <groupId>.
  • In a multi-module project, put pluginManagement in the parent POM so every module uses the same versions.

Create a Multi-Module Maven Project

Larger applications are split into modules: separate Maven projects built together by one parent (or aggregator) POM. A common split is a core module with business logic and an app module that uses it.

todo-parent/
├── pom.xml              <- packaging pom, lists the modules
├── todo-core/
│   ├── pom.xml
│   └── src/main/java/com/gocourse/todo/core/Task.java
└── todo-app/
    ├── pom.xml          <- depends on todo-core
    └── src/main/java/com/gocourse/todo/app/App.java
<!-- todo-parent/pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gocourse</groupId>
  <artifactId>todo-parent</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>todo-core</module>
    <module>todo-app</module>
  </modules>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>
<!-- todo-app/pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.gocourse</groupId>
    <artifactId>todo-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>todo-app</artifactId>

  <dependencies>
    <dependency>
      <groupId>com.gocourse</groupId>
      <artifactId>todo-core</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>

The todo-core/pom.xml looks the same, with <artifactId>todo-core</artifactId> and no dependencies. Build everything from the parent folder:

cd todo-parent
mvn install

Output (end of the log):

[INFO] Reactor Summary for todo-parent 1.0.0-SNAPSHOT:
[INFO]
[INFO] todo-parent ........................................ SUCCESS [  0.152 s]
[INFO] todo-core .......................................... SUCCESS [  1.874 s]
[INFO] todo-app ........................................... SUCCESS [  0.611 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

How it works:

  • <packaging>pom</packaging> means the parent produces no JAR; it only groups modules and shares settings.
  • Each module inherits groupId, version and the properties from <parent>, so they are not repeated.
  • The reactor reads all modules and sorts them by dependency: todo-core is built before todo-app because the app depends on it.
  • Use mvn -pl todo-app -am package to build one module plus the modules it needs (-am means "also make").

Real-World Example: Create a Maven Project for a To-Do CLI

This single-module project is a command-line to-do list. You pass tasks as arguments, and tasks ending in :done are marked complete. It uses a record, a JUnit test, pinned plugins, resource filtering to print the project version, and an executable JAR.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.gocourse</groupId>
  <artifactId>todo-cli</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>25</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>6.1.3</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering> <!-- replace ${...} placeholders -->
      </resource>
    </resources>

    <pluginManagement>
      <plugins>
        <plugin><artifactId>maven-compiler-plugin</artifactId><version>3.15.0</version></plugin>
        <plugin><artifactId>maven-resources-plugin</artifactId><version>3.4.0</version></plugin>
        <plugin><artifactId>maven-surefire-plugin</artifactId><version>3.5.6</version></plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.5.0</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.gocourse.todo.App</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
# src/main/resources/app.properties
app.version=${project.version}
package com.gocourse.todo;

public record Task(String title, boolean done) {

    public Task {
        if (title == null || title.isBlank()) {
            throw new IllegalArgumentException("Task title is required");
        }
        title = title.strip();
    }

    /** "Write tests" -> open task, "Install JDK:done" -> finished task. */
    public static Task parse(String text) {
        if (text.endsWith(":done")) {
            return new Task(text.substring(0, text.length() - ":done".length()), true);
        }
        return new Task(text, false);
    }
}
package com.gocourse.todo;

import java.util.ArrayList;
import java.util.List;

public class TaskList {
    private final List<Task> tasks = new ArrayList<>();

    public void add(Task task) {
        tasks.add(task);
    }

    public long doneCount() {
        return tasks.stream().filter(Task::done).count();
    }

    public List<String> render() {
        List<String> lines = new ArrayList<>();
        for (int i = 0; i < tasks.size(); i++) {
            Task task = tasks.get(i);
            lines.add((i + 1) + ". [" + (task.done() ? "x" : " ") + "] " + task.title());
        }
        lines.add(doneCount() + " of " + tasks.size() + " tasks done");
        return lines;
    }
}
package com.gocourse.todo;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App {
    public static void main(String[] args) throws IOException {
        System.out.println("Todo CLI " + appVersion());
        if (args.length == 0) {
            System.out.println("Usage: java -jar todo-cli.jar \"task\" \"finished task:done\" ...");
            return;
        }
        TaskList taskList = new TaskList();
        for (String argument : args) {
            taskList.add(Task.parse(argument));
        }
        taskList.render().forEach(System.out::println);
    }

    static String appVersion() throws IOException {
        Properties properties = new Properties();
        try (InputStream in = App.class.getResourceAsStream("/app.properties")) {
            properties.load(in);
        }
        return properties.getProperty("app.version");
    }
}
package com.gocourse.todo;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import org.junit.jupiter.api.Test;

class TaskListTest {

    @Test
    void parsesDoneSuffix() {
        Task task = Task.parse("Install JDK:done");
        assertEquals("Install JDK", task.title());
        assertTrue(task.done());
    }

    @Test
    void blankTitleIsRejected() {
        assertThrows(IllegalArgumentException.class, () -> Task.parse("   "));
    }

    @Test
    void rendersNumberedListWithSummary() {
        TaskList taskList = new TaskList();
        taskList.add(Task.parse("Install JDK:done"));
        taskList.add(Task.parse("Write tests"));

        assertEquals(List.of(
                "1. [x] Install JDK",
                "2. [ ] Write tests",
                "1 of 2 tasks done"), taskList.render());
    }
}

Build and run:

mvn clean package
java -jar target/todo-cli-1.0.0.jar "Install JDK:done" "Create Maven project:done" "Write tests"

Output (Maven log shortened):

[INFO] Running com.gocourse.todo.TaskListTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] Building jar: /home/asha/todo-cli/target/todo-cli-1.0.0.jar
[INFO] BUILD SUCCESS
Todo CLI 1.0.0
1. [x] Install JDK
2. [x] Create Maven project
3. [ ] Write tests
2 of 3 tasks done

How it works:

  1. Resource filtering. With <filtering>true</filtering>, Maven replaces ${project.version} in app.properties with 1.0.0 while copying it. Change the version in the POM and the app reports the new version automatically.
  2. Pinned plugins. pluginManagement fixes the compiler, resources and Surefire versions, while the JAR plugin is configured directly in <plugins> with its mainClass.
  3. A validating record. The compact constructor of Task rejects blank titles and strips spaces, so every Task object is valid.
  4. Tests guard the build. The three tests run during package. If render() printed the wrong format, the build would stop and no JAR would be created.
  5. Executable JAR. The manifest's Main-Class lets java -jar start App, which reads the arguments and prints the list.

This project has no external libraries yet. The next lesson, Maven Dependencies, shows how to add libraries, choose scopes and manage versions. To learn more about the JAR file Maven produced, see JAR File in Java.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Create a Maven Project in Java and get answers drawn from it.

Signed-in readers only.