Maven
Build lifecycle, POM, dependency management, plugins, and the Maven repository structure
- Understand the Maven build lifecycle phases
- Configure project dependencies in pom.xml
- Use plugins to compile, test, and package Spring Boot applications
Spring Boot Series | Concept and Coding
Table of Contents
- What is Maven?
- Maven vs Ant
- POM — Project Object Model
- Maven Project Structure
- Reading pom.xml — Element by Element
- Maven Build Lifecycle
- Phase 1 — Validate
- Phase 2 — Compile
- Phase 3 — Test
- Phase 4 — Package
- Phase 5 — Verify
- Phase 6 — Install
- Phase 7 — Deploy
- Local vs Remote Repository
- Plugins and Goals (Deep Dive)
- settings.xml
- Key Diagrams
- Interview Notes
- Common Mistakes
- Summary Cheat Sheet
1. What is Maven?
Overview
Maven is commonly misunderstood as just a "build tool" — something that generates a JAR file. In reality, Maven is a project management tool that handles a wide range of developer tasks throughout a project's lifecycle.
Why This Concept Exists
Before Maven, developers had to manually manage:
- Downloading third-party libraries (JAR files)
- Telling the build tool exactly how to compile, test, and package code (step by step)
- Documenting the project
- Managing dependencies between libraries
Maven was created to automate and standardize all of these activities so that developers can focus on writing code.
Definition
Maven
is an open-source project management and build automation tool primarily used for Java projects. It uses a Project Object Model (POM) defined in pom.xml to describe the project, its dependencies, and its build process.
What Maven Provides
| Feature | Description |
|---|---|
| Build Generation | Compiles code, runs tests, creates JAR/WAR files |
| Dependency Resolution | Automatically downloads required libraries |
| Documentation | Can generate project documentation |
| Project Structure | Enforces a standard directory layout |
| Lifecycle Management | Defines ordered phases from validate → deploy |
| Plugin System | Extensible via plugins for custom tasks |
Real-World Analogy
Think of Maven as a project manager at a construction site. You tell the project manager: "Build the house." You don't need to explain how to pour the foundation, lay bricks, or wire electricity. The project manager knows the steps, the order, and how to do each one. You only declare what you want — Maven handles the how.
2. Maven vs Ant
Background
Before Maven, Apache Ant was the dominant build tool for Java projects. Understanding why Maven replaced Ant for most use cases helps clarify Maven's design philosophy.
The Core Difference
| Aspect | Ant | Maven |
|---|---|---|
| Approach | Imperative (tell what AND how) | Declarative (tell only what) |
| Configuration | build.xml with explicit steps | pom.xml with goals and lifecycle |
| Convention | None — you define everything | Convention over configuration |
| Dependency management | Manual (download JARs yourself) | Automatic (Maven downloads from Central) |
| Learning curve | Lower initially, harder to maintain | Steeper initially, easier long-term |
Ant Example (Compile Task)
In Ant, you had to explicitly instruct the tool what to do AND exactly how to do it:
1<!-- Ant build.xml — must specify source, destination, and the javac compiler explicitly -->2<target name="compile">3 <javac srcdir="src/main/java"4 destdir="target/classes"5 executable="javac" />6</target>Every attribute — where the source is, where to put the output, which compiler to use — had to be manually specified.
Maven Equivalent
In Maven, you simply run:
1mvn compileMaven already knows:
- Where to find source files (
src/main/java) - Where to put compiled classes (
target/classes) - How to invoke the Java compiler
This knowledge is built into Maven's conventions and plugins. You declare the goal; Maven figures out the steps.
3. POM Project Object Model
Definition
The POM (Project Object Model) is the core concept of Maven. It is represented as an XML file named pom.xml and contains all the information Maven needs to build and manage a project.
Every Maven command you run first looks for `pom.xml` in the current directory.
The POM Hierarchy
Every pom.xml in Maven is part of a hierarchy. No POM exists in isolation.
1Super POM (Built into Maven — the ultimate parent of all POMs)2 │3 └── Spring Boot Starter Parent POM4 │5 └── Your Project's pom.xml ← This is what you writeRules of the Hierarchy
- If your
pom.xmldefines a, it inherits all configurations, dependencies, and plugin settings from that parent POM. - If no
is specified, Maven automatically makes your POM a child of the Super POM. - The Super POM is the ultimate root of all inheritance and contains default configurations like the Maven Central repository URL.
pom.xml can be small and still work — it inherits a lot of configuration from its parent and ultimately from the Super POM.You can view Maven's Super POM at: https://maven.apache.org/ref/3.x.x/maven-model-builder/super-pom.html
4. Maven Project Structure
Standard Directory Layout
Maven enforces a standard project structure. This is one of its core conventions. When you generate a Spring Boot project (with Maven selected), the following structure is created:
1your-app-name/2├── pom.xml ← Project configuration3└── src/4 ├── main/5 │ └── java/6 │ └── com/7 │ └── conceptandcoding/8 │ └── learningspringboot/9 │ └── LearningSpringBootApplication.java10 └── test/11 └── java/12 └── com/13 └── conceptandcoding/14 └── learningspringboot/15 └── LearningSpringBootApplicationTests.javaDirectory Explanation
| Directory | Purpose |
|---|---|
src/main/java | Your application source code |
src/main/resources | Configuration files (e.g., application.properties) |
src/test/java | Unit and integration test code |
src/test/resources | Test-specific resources |
target/ | Generated by Maven — compiled classes, JARs, reports |
pom.xml | Maven project configuration |
target/ directory is auto-generated by Maven during the build. You should never commit this to version control (add it to .gitignore).How the Package Structure is Generated
When creating a Spring Boot project, you provide three values:
| Field | Example Value | Role |
|---|---|---|
| Group ID | com.conceptandcoding | Company/organization identifier |
| Artifact ID | learningspringboot | Project/module name |
| Version | 0.0.1-SNAPSHOT | Current version |
Maven uses Group ID to create the nested package folder structure under src/main/java. So com.conceptandcoding becomes:
1src/main/java/com/conceptandcoding/learningspringboot/The same mirrored structure is created under src/test/java — every main class has a corresponding test class location.
5. Reading pom.xml Element by Element
Below is a typical pom.xml for a Spring Boot project, annotated section by section.
1<?xml version="1.0" encoding="UTF-8"?>2<project xmlns="http://maven.apache.org/POM/4.0.0"3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.05 https://maven.apache.org/xsd/maven-4.0.0.xsd">6
7 <modelVersion>4.0.0</modelVersion>8
9 <!-- 1. PARENT -->10 <parent>11 <groupId>org.springframework.boot</groupId>12 <artifactId>spring-boot-starter-parent</artifactId>13 <version>3.1.0</version>14 <relativePath/>15 </parent>16
17 <!-- 2. PROJECT COORDINATES -->18 <groupId>com.conceptandcoding</groupId>19 <artifactId>learningspringboot</artifactId>20 <version>0.0.1-SNAPSHOT</version>21
22 <!-- 3. PROPERTIES -->23 <properties>24 <java.version>17</java.version>25 </properties>26
27 <!-- 4. DEPENDENCIES -->28 <dependencies>29 <dependency>30 <groupId>org.springframework.boot</groupId>31 <artifactId>spring-boot-starter-web</artifactId>32 </dependency>33
34 <dependency>35 <groupId>org.springframework.boot</groupId>36 <artifactId>spring-boot-starter-test</artifactId>37 <scope>test</scope>38 </dependency>39 </dependencies>40
41 <!-- 5. BUILD (optional — for custom plugins/tasks) -->42 <build>43 <plugins>44 <!-- custom plugins go here -->45 </plugins>46 </build>47
48</project>5.1 Schema Declaration
1<project xmlns="http://maven.apache.org/POM/4.0.0"2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 ...">Purpose: Specifies the XML schema that this POM file must conform to. The schema defines:
- What elements are valid inside
- What elements are valid inside
,, etc. - The correct nesting rules
If you try to put an arbitrary element (e.g., ) in a place where the schema doesn't allow it, Maven will reject it.
5.2 `<parent>`
1<parent>2 <groupId>org.springframework.boot</groupId>3 <artifactId>spring-boot-starter-parent</artifactId>4 <version>3.1.0</version>5 <relativePath/>6</parent>Purpose: Declares the parent POM. Your project inherits all configurations, dependency versions, and plugin configurations from this parent.
What is inherited?
- Plugin versions and configurations
- Dependency management (versions of common libraries)
- Build settings
- Java version defaults
This is why your own pom.xml doesn't need to specify versions for Spring Boot dependencies — the parent already declares them.
spring-boot-starter-parent POM online, you will find hundreds of pre-configured dependency versions. Because your project inherits from it, you get all of that for free.5.3 Project Coordinates: `<groupId>`, `<artifactId>`, `<version>`
1<groupId>com.conceptandcoding</groupId>2<artifactId>learningspringboot</artifactId>3<version>0.0.1-SNAPSHOT</version>These three elements together form a unique identifier for your project in the Maven ecosystem. They are called Maven Coordinates or GAV Coordinates.
| Element | Meaning | Convention |
|---|---|---|
groupId | Organization or company | Reverse domain: com.google, org.apache |
artifactId | Project or module name | Lowercase, hyphenated: spring-boot-web |
version | Current version | Semantic versioning: 1.0.0, 2.3.1-SNAPSHOT |
SNAPSHOT means this is a development/in-progress version. A version without SNAPSHOT (e.g., 1.0.0) is a release version.
5.4 `<properties>`
1<properties>2 <java.version>17</java.version>3</properties>Purpose: Key-value pairs for configuration values that can be referenced anywhere in the POM using the ${key} syntax.
How to Use a Property
1<properties>2 <java.version>17</java.version>3 <project.encoding>UTF-8</project.encoding>4</properties>5
6<dependencies>7 <dependency>8 <groupId>com.example</groupId>9 <artifactId>my-lib</artifactId>10 <version>${java.version}</version> <!-- resolves to "17" -->11 </dependency>12</dependencies>When Maven processes the POM, it replaces ${java.version} with 17.
Benefits:
- Avoids repeating the same version number in multiple places
- Changing the value in one place updates it everywhere
- Makes the POM easier to read and maintain
5.5 `<repositories>`
1<repositories>2 <repository>3 <id>central</id>4 <url>https://repo.maven.apache.org/maven2</url>5 </repository>6</repositories>Purpose: Tells Maven where to download dependencies from.
pom.xml because the Maven Central URL is already defined in the Super POM. Maven inherits it automatically. This element is only needed when you want to add an additional or custom repository (e.g., your company's private Nexus or Artifactory server).5.6 `<dependencies>`
1<dependencies>2 <dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-web</artifactId>5 </dependency>6</dependencies>Purpose: Declares the libraries your project needs. Maven will automatically download these and make them available on the classpath.
Each is identified by the same GAV coordinates (groupId, artifactId, version).
Dependency Scope — Controls when the dependency is available:
| Scope | Meaning |
|---|---|
compile (default) | Available at compile time and runtime |
test | Only available during testing |
provided | Available at compile time but NOT packaged (e.g., servlet API — provided by the server) |
runtime | Not needed at compile time, but needed at runtime |
5.7 `<build>` and `<plugins>`
1<build>2 <plugins>3 <plugin>4 <groupId>org.apache.maven.plugins</groupId>5 <artifactId>maven-checkstyle-plugin</artifactId>6 <version>3.2.0</version>7 <executions>8 <execution>9 <phase>validate</phase>10 <goals>11 <goal>check</goal>12 </goals>13 </execution>14 </executions>15 <configuration>16 <configLocation>my-code-styles.xml</configLocation>17 </configuration>18 </plugin>19 </plugins>20</build>Purpose: Used to add custom tasks (plugins/goals) to specific phases of the Maven build lifecycle.
This is where Maven's real power becomes visible — you can hook in any behavior at any point in the lifecycle.
6. Maven Build Lifecycle
Overview
The Maven Build Lifecycle is a defined sequence of phases that Maven executes in strict order. Understanding this is the most important concept in Maven.
The 7 Phases
11. validate → 2. compile → 3. test → 4. package → 5. verify → 6. install → 7. deploySequential Execution Rule
mvn package triggers: validate → compile → test → packageThis means you can't skip phases. Running mvn deploy runs all 7 phases.
Phases and Goals
Each phase contains one or more goals. A goal is a specific task within a phase.
1Phase: compile2 └── Goal 1: compiler:compile (compiles Java source files)3
4Phase: test5 └── Goal 1: surefire:test (runs unit tests)6
7Phase: package8 └── Goal 1: jar:jar (creates JAR file)Running a specific goal directly:
1mvn compiler:compile # Run just this goal, not the full phase2mvn surefire:test # Run just the test goalRunning a phase (runs all goals in the phase, plus all preceding phases):
1mvn compile2mvn test3mvn packageBuild Lifecycle Diagram
7. Phase 1 Validate
Purpose
The validate phase checks that the project structure is correct and all necessary information is available before the build begins.
Default behavior: Maven's default validate phase does very little on its own. It doesn't enforce code style or complex structural rules unless you add a plugin.
Adding Custom Validation with a Plugin
A common use case is enforcing code style using the Checkstyle plugin:
1<build>2 <plugins>3 <plugin>4 <groupId>org.apache.maven.plugins</groupId>5 <artifactId>maven-checkstyle-plugin</artifactId>6 <version>3.2.0</version>7 <executions>8 <execution>9 <phase>validate</phase> <!-- Hook into validate phase -->10 <goals>11 <goal>check</goal> <!-- The task to run -->12 </goals>13 </execution>14 </executions>15 <configuration>16 <configLocation>my-code-styles.xml</configLocation>17 </configuration>18 </plugin>19 </plugins>20</build>What this does:
- Before any compilation, Maven checks if the code follows the style rules defined in
my-code-styles.xml - If violations are found, the build fails early — before wasting time compiling bad code
- Different companies have different style guides; this enforces them automatically
Command to trigger:
1mvn validate8. Phase 2 Compile
Purpose
Converts Java source code (.java files) into bytecode (.class files) that the JVM can execute.
Command:
1mvn compileWhat runs: validate → compile
What Happens Internally
When you run mvn compile:
- Maven looks for
pom.xml - Maven finds the
maven-compiler-plugin(defined in Super POM or parent) - The plugin runs
javacinternally on all.javafiles insrc/main/java - Compiled
.classfiles are placed intarget/classes/
javac. Maven's compiler plugin knows how to do this. You only said compile — Maven figured out how.Output Location
1Before mvn compile:2your-project/3├── pom.xml4└── src/main/java/com/conceptandcoding/.../YourClass.java5
6After mvn compile:7your-project/8├── pom.xml9├── src/main/java/...10└── target/11 └── classes/12 └── com/conceptandcoding/.../YourClass.class ← Generated bytecodeAnt vs Maven Comparison (Compile)
1<!-- ANT — must specify everything explicitly -->2<target name="compile">3 <javac srcdir="${src.dir}"4 destdir="${build.dir}"5 executable="javac" />6</target>1# MAVEN — just declare the goal2mvn compile9. Phase 3 Test
Purpose
Runs all unit tests in the src/test/java directory using a testing framework (typically JUnit).
Command:
1mvn testWhat runs: validate → compile → test
Test Class Structure
Maven expects test classes in the mirror structure of main:
1src/2├── main/java/com/conceptandcoding/learningspringboot/3│ └── LearningSpringBootApplication.java4└── test/java/com/conceptandcoding/learningspringboot/5 └── LearningSpringBootApplicationTests.java ← Test class for the aboveExample Test Class
1package com.conceptandcoding.learningspringboot;2
3import org.junit.jupiter.api.Test;4import org.springframework.boot.test.context.SpringBootTest;5
6@SpringBootTest7class LearningSpringBootApplicationTests {8
9 @Test10 void contextLoads() {11 System.out.println("Concept and Coding — Test case running!");12 }13}Expected output during mvn test:
1[INFO] Running com.conceptandcoding.learningspringboot.LearningSpringBootApplicationTests2Concept and Coding — Test case running!3[INFO] Tests run: 1, Failures: 0, Errors: 04[INFO] BUILD SUCCESSWhat Maven Does During Test Phase
- Compiles test classes (if not already compiled)
- Uses the Surefire plugin to run all test classes
- Generates test reports under
target/surefire-reports/ - If any test fails, the build stops with
BUILD FAILURE
bash
mvn package -DskipTests
``10. Phase 4 Package
Purpose
Takes the compiled bytecode (.class files) and packages them into a distributable format — typically a JAR file (or WAR for web applications).
Command:
1mvn packageWhat runs: validate → compile → test → package
What is a JAR?
A JAR (Java ARchive) is a ZIP file containing:
- All compiled
.classfiles - Resources (images, config files, etc.)
META-INF/MANIFEST.MF— metadata about the JAR
For Spring Boot applications, the JAR is a "fat JAR" or "uber JAR" — it includes all dependencies, making it fully self-contained and directly executable.
Output Location
1target/2├── classes/ ← Compiled classes (from compile phase)3└── learningspringboot-0.0.1-SNAPSHOT.jar ← The packaged JAR (from package phase)JAR Naming Convention
1{artifactId}-{version}.jar2
3Example: learningspringboot-0.0.1-SNAPSHOT.jarWhat You Can Do with the JAR
| Action | Command |
|---|---|
| Run the application | java -jar learningspringboot-0.0.1-SNAPSHOT.jar |
| Share with teammates | Send the .jar file |
| Deploy to a server | Copy to server and run |
| Add as dependency | Install to local/remote repository |
Specifying Package Type in pom.xml
1<packaging>jar</packaging> <!-- default — creates .jar -->2<!-- or -->3<packaging>war</packaging> <!-- for web apps deployed on Tomcat/Wildfly -->11. Phase 5 Verify
Purpose
Runs checks to verify that the packaged artifact is valid and meets quality criteria. This phase is designed for integration tests and static analysis.
Command:
1mvn verifyWhat runs: validate → compile → test → package → verify
Default Behavior
Like validate, Maven's default verify phase does very little unless you add plugins.
Adding Static Code Analysis with PMD
PMD is a popular static analysis tool that detects:
- Unused variables
- Unused imports
- Empty catch blocks
- Duplicate code
- Dead code
- Overly complex methods
1<build>2 <plugins>3 <plugin>4 <groupId>org.apache.maven.plugins</groupId>5 <artifactId>maven-pmd-plugin</artifactId>6 <version>3.20.0</version>7 <executions>8 <execution>9 <phase>verify</phase> <!-- Hook into verify phase -->10 <goals>11 <goal>pmd</goal> <!-- Run PMD analysis -->12 </goals>13 </execution>14 </executions>15 </plugin>16 </plugins>17</build>What this does:
- After packaging, Maven runs PMD on all source files
- Issues are reported as warnings or errors
- If configured strictly, violations fail the build
Other Common Verify Plugins
| Plugin | Purpose |
|---|---|
| PMD | Static code analysis |
| SpotBugs | Bug detection |
| JaCoCo | Code coverage reporting |
| OWASP Dependency Check | Security vulnerability scanning |
12. Phase 6 Install
Purpose
Copies the packaged JAR file from the target/ directory into your local Maven repository (~/.m2/repository/). Once installed locally, any other project on your machine can use it as a dependency.
Command:
1mvn installWhat runs: validate → compile → test → package → verify → install
What is the Local Repository?
The local repository is a directory on your own machine where Maven stores:
- All downloaded dependencies (cached so they don't need to be re-downloaded)
- JARs you have installed locally with
mvn install
Default location:
| OS | Path |
|---|---|
| macOS / Linux | ~/.m2/repository/ |
| Windows | C:\Users\YourName\.m2\repository\ |
Repository Directory Structure
After running mvn install on our example project:
1~/.m2/repository/2└── com/3 └── conceptandcoding/4 └── learningspringboot/5 └── 0.0.1-SNAPSHOT/6 ├── learningspringboot-0.0.1-SNAPSHOT.jar7 └── learningspringboot-0.0.1-SNAPSHOT.pomThe path mirrors the GAV coordinates: groupId/artifactId/version/.
Why Install to Local Repository?
Scenario: You have two projects, A and B. Project B depends on Project A.
1Project A (library) → mvn install → stored in ~/.m2/2 ↓3Project B (app) → declares A as dependency → Maven finds it in ~/.m2/Without mvn install, Project B cannot find Project A's JAR unless it's on Maven Central.
Customizing the Local Repository Path
In ~/.m2/settings.xml, you can override the default local repository path:
1<settings>2 <localRepository>/path/to/my/custom/repository</localRepository>3</settings>After this change, all installed JARs go to your custom path instead of the default ~/.m2/repository/.
13. Phase 7 Deploy
Purpose
Copies the packaged JAR to a remote repository — either your company's internal repository manager (Nexus, Artifactory) or Maven Central — so that others can use it as a dependency.
Command:
1mvn deployWhat runs: All 7 phases (validate → compile → test → package → verify → install → deploy)
Configuring the Remote Repository
To deploy, you must tell Maven where to upload the artifact. This is done via in pom.xml:
1<distributionManagement>2 <repository>3 <id>company-releases</id>4 <url>https://nexus.mycompany.com/repository/maven-releases/</url>5 </repository>6 <snapshotRepository>7 <id>company-snapshots</id>8 <url>https://nexus.mycompany.com/repository/maven-snapshots/</url>9 </snapshotRepository>10</distributionManagement>Authentication for Remote Repository
You can't upload to a remote repository without credentials. Credentials are stored in settings.xml (NOT in pom.xml — never put passwords in version-controlled files):
1<!-- ~/.m2/settings.xml -->2<settings>3 <servers>4 <server>5 <id>company-releases</id> <!-- Must match <id> in distributionManagement -->6 <username>your-username</username>7 <password>your-password</password>8 </server>9 </servers>10</settings>The in must exactly match the in .
Error When distributionManagement is Missing
If you run mvn deploy without configuring :
1[ERROR] BUILD FAILURE2[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin3Deployment failure — repository element was not specified in the POM inside4distributionManagement element.Deploying to Maven Central
If you want to publish an open-source library to Maven Central:
1<distributionManagement>2 <repository>3 <id>maven-central</id>4 <url>https://repo.maven.apache.org/maven2</url>5 </repository>6</distributionManagement>14. Local vs Remote Repository
Repository Architecture Diagram
Dependency Resolution Order
When Maven needs a dependency:
- Check local repository (
~/.m2/repository/)
- If found → use it (no network call)
- If not found → go to step 2
- Check remote repository (Maven Central or configured URL)
- Download the JAR
- Cache it in local repository
- Use it
- Future builds → found in local repository (no re-download needed)
Comparison Table
| Aspect | Local Repository | Remote Repository |
|---|---|---|
| Location | Your machine (~/.m2/) | External server |
| Purpose | Cache + locally installed JARs | Shared, team-wide artifact storage |
| Access | Instant (filesystem) | Network required |
| Write | mvn install | mvn deploy |
| Configuration | settings.xml | pom.xml |
| Examples | ~/.m2/repository/ | Maven Central, Nexus, Artifactory |
15. Plugins and Goals (Deep Dive)
What is a Plugin?
A Maven plugin is a collection of goals (tasks). Plugins extend Maven's built-in capabilities.
1Plugin: maven-compiler-plugin2 Goal: compile ← compiles main sources3 Goal: testCompile ← compiles test sources4
5Plugin: maven-surefire-plugin6 Goal: test ← runs unit tests7
8Plugin: maven-jar-plugin9 Goal: jar ← creates the JARDefault Lifecycle Bindings
Maven's built-in lifecycle phases are already bound to default plugin goals:
| Phase | Default Plugin | Default Goal |
|---|---|---|
| compile | maven-compiler-plugin | compile |
| test | maven-surefire-plugin | test |
| package | maven-jar-plugin | jar |
| install | maven-install-plugin | install |
| deploy | maven-deploy-plugin | deploy |
These default bindings come from the Super POM. You don't need to declare them.
Running a Goal Directly
You can run any goal directly without going through the lifecycle phases:
1mvn compiler:compile # plugin-name:goal-name syntax2mvn surefire:test3mvn dependency:tree # Show dependency tree4mvn dependency:resolve # Download all dependenciesAdding a Custom Plugin (Full Example)
1<build>2 <plugins>3 <plugin>4 <!-- Where to find this plugin -->5 <groupId>org.apache.maven.plugins</groupId>6 <artifactId>maven-pmd-plugin</artifactId>7 <version>3.20.0</version>8
9 <!-- What to execute and when -->10 <executions>11 <execution>12 <id>pmd-analysis</id> <!-- Unique name for this execution -->13 <phase>verify</phase> <!-- When to run it -->14 <goals>15 <goal>pmd</goal> <!-- Which goal (task) to run -->16 </goals>17 </execution>18 </executions>19
20 <!-- Plugin-specific settings -->21 <configuration>22 <failOnViolation>true</failOnViolation>23 <printFailingErrors>true</printFailingErrors>24 </configuration>25 </plugin>26 </plugins>27</build>16. settings.xml
Overview
settings.xml is Maven's global or user-level configuration file. It is separate from pom.xml and stored in the Maven home directory.
Location:
1~/.m2/settings.xml ← User-level (most common)2$MAVEN_HOME/conf/settings.xml ← System-level (applies to all users)What settings.xml Configures
1<settings>2
3 <!-- 1. Override default local repository path -->4 <localRepository>/custom/path/to/repo</localRepository>5
6 <!-- 2. Proxy settings for corporate networks -->7 <proxies>8 <proxy>9 <id>company-proxy</id>10 <active>true</active>11 <protocol>http</protocol>12 <host>proxy.mycompany.com</host>13 <port>8080</port>14 </proxy>15 </proxies>16
17 <!-- 3. Server credentials for remote repositories -->18 <servers>19 <server>20 <id>company-nexus</id>21 <username>deploy-user</username>22 <password>s3cr3t</password>23 </server>24 </servers>25
26 <!-- 4. Mirror — redirect repository requests to a different URL -->27 <mirrors>28 <mirror>29 <id>company-mirror</id>30 <mirrorOf>central</mirrorOf>31 <url>https://nexus.mycompany.com/repository/maven-central/</url>32 </mirror>33 </mirrors>34
35</settings>pom.xml. It gets committed to version control. Always use settings.xml, which stays on your local machine.17. Key Diagrams
Maven Build Lifecycle Sequence
POM Inheritance Hierarchy
Dependency Resolution Flow
Full Maven Architecture Mind Map
18. Interview Notes
Common Interview Questions and Answers
Q1: What is Maven? Is it just a build tool?
Answer: No. Maven is a project management tool. Build generation is only one of its capabilities. It also handles dependency resolution, project documentation, lifecycle management, and plugin-based extensibility.
Q2: What is POM? What is Super POM?
Answer: POM stands for Project Object Model. It is the pom.xml file that describes your project to Maven. The Super POM is the ultimate parent of all POMs — every pom.xml implicitly inherits from it if no explicit parent is defined.
Q3: What is the Maven Build Lifecycle?
Answer: A sequence of 7 ordered phases:
- validate → 2. compile → 3. test → 4. package → 5. verify → 6. install → 7. deploy
Each phase is sequential — running any phase also runs all preceding phases.
Q4: What is the difference between `mvn install` and `mvn deploy`?
mvn install | mvn deploy |
|---|---|
Copies JAR to local repository (~/.m2/) | Copies JAR to remote repository |
| Available only on your machine | Available to the whole team |
| No credentials needed | Credentials required |
Q5: What is the difference between a Phase and a Goal?
Answer: A phase is a step in the build lifecycle (e.g., compile, test, package). A goal is a specific task within a phase, executed by a plugin (e.g., compiler:compile, surefire:test). Multiple goals can be bound to a single phase.
Q6: Where are downloaded dependencies stored?
Answer: In the local repository, typically at ~/.m2/repository/ on macOS/Linux or C:\Users\Name\.m2\repository\ on Windows.
Q7: What is the `<parent>` element in pom.xml?
Answer: It declares the parent POM from which the current project inherits configurations. For Spring Boot projects, the parent is spring-boot-starter-parent, which provides pre-configured dependency versions, plugin settings, and build conventions.
Q8: What happens when you run `mvn test`?
Answer: Maven runs: validate → compile → test. It compiles main and test sources, then uses the Surefire plugin to execute all JUnit/TestNG test classes in src/test/java/. If any test fails, the build fails.
Q9: How do you skip tests during a build?
1mvn package -DskipTests # Skip test execution (still compiles tests)2mvn package -Dmaven.test.skip=true # Skip compilation AND execution of testsQ10: What is `<distributionManagement>`?
Answer: An element in pom.xml that specifies the remote repository URL where mvn deploy will upload the artifact. Without it, mvn deploy fails with a configuration error.
19. Common Mistakes
Mistake 1: Forgetting Sequential Phase Execution
1# ❌ Wrong assumption: "I want ONLY the package phase to run"2mvn package3
4# ✅ Reality: validate, compile, test, and THEN package all runMistake 2: Putting Credentials in pom.xml
1<!-- ❌ NEVER DO THIS — pom.xml goes into version control -->2<distributionManagement>3 <repository>4 <id>company-repo</id>5 <url>https://nexus.company.com/repo</url>6 <username>admin</username> <!-- WRONG! -->7 <password>secret</password> <!-- WRONG! -->8 </repository>9</distributionManagement>1<!-- ✅ Correct — credentials go in ~/.m2/settings.xml -->2<servers>3 <server>4 <id>company-repo</id> <!-- Must match <id> in distributionManagement -->5 <username>admin</username>6 <password>secret</password>7 </server>8</servers>Mistake 3: Running `mvn deploy` Without `<distributionManagement>`
Result: Build fails with:
1Deployment failure — repository element was not specified in the POM2inside distributionManagement element.Fix: Add with the remote repository URL.
Mistake 4: Editing the `target/` Directory
The target/ directory is generated by Maven and overwritten on every build. Never manually edit files there.
Mistake 5: Committing `target/` to Version Control
Add to .gitignore:
1target/Mistake 6: Using the Same `<id>` for Different Servers in settings.xml
The in must exactly match the in inside . Mismatches cause authentication failures silently.
20. Summary Cheat Sheet
Maven Commands Quick Reference
| Command | Phases Executed | Output |
|---|---|---|
mvn validate | validate | Validation report |
mvn compile | validate → compile | .class files in target/classes/ |
mvn test | validate → compile → test | Test results in target/surefire-reports/ |
mvn package | validate → compile → test → package | .jar in target/ |
mvn verify | validate → ... → verify | Quality analysis reports |
mvn install | validate → ... → install | JAR copied to ~/.m2/ |
mvn deploy | All 7 phases | JAR uploaded to remote repository |
mvn clean | (separate) | Deletes target/ directory |
mvn clean package | clean + all through package | Fresh build with JAR |
pom.xml Key Elements
| Element | Purpose |
|---|---|
| Inherit from parent POM |
| Organization identifier |
| Project name |
| Project version |
| Reusable key-value config values |
| Required libraries |
| Where to download dependencies from |
| Custom tasks hooked into phases |
| Where to deploy the artifact |
Lifecycle Summary
1validate → Validate project structure2compile → .java → .class (bytecode)3test → Run unit tests (JUnit/TestNG)4package → .class → .jar / .war5verify → Static analysis, integration tests6install → Copy JAR to ~/.m2/repository/7deploy → Upload JAR to remote repositoryRepository Summary
1Local Repository = ~/.m2/repository/ (your machine, fast)2Remote Repository = Maven Central (public, internet)3 = Company Nexus/Artifactory (team, intranet)4
5Dependency lookup order: Local → Remote → Cache locally → Use plugins when you need to go beyond the defaults.Study Guide — Maven | Spring Boot Series | Concept and Coding
Mastery check
How well can you recall this?
Finished this lesson?