What it is
Maven is a build automation and project management tool used primarily for Java projects, simplifying dependency management, compilation, testing, and packaging.
Installation
Linux
# Using package manager (Debian/Ubuntu)
sudo apt update
sudo apt install maven
# Using package manager (Fedora/CentOS/RHEL)
sudo yum install maven
# or
sudo dnf install maven
# Downloading from Apache Maven website
# Check https://maven.apache.org/download.cgi for latest version
wget https://dlcdn.apache.org/maven/maven-3/3.9.6/binar
y/apache-maven-3.9.6-bin.tar.gz
tar xzvf apache-maven-3.9.6-bin.tar.gz
export M2_HOME=/path/to/apache-maven-3.9.6
export PATH=$M2_HOME/bin:$PATH
# Add these exports to your shell profile (~/.bashrc, ~/.zshrc) for persistence
macOS
# Using Homebrew
brew install maven
Windows
# Downloading from Apache Maven website
# Check https://maven.apache.org/download.cgi for latest version
# Download the .zip file, extract it to a directory (e.g., C:\Program Files\Maven)
# Set M2_HOME environment variable to the extracted directory (e.g., C:\Program Files\Maven\apache-maven-3.9.6)
# Add %M2_HOME%\bin to your system's PATH environment variable
Core Concepts
- Project Object Model (POM): The
pom.xmlfile is the central configuration file for a Maven project. It describes the project’s structure, dependencies, build process, plugins, and more. - Dependencies: Maven manages external libraries (JARs) your project needs. You declare them in the
pom.xml, and Maven downloads them from repositories (like Maven Central). - Build Lifecycle: Maven has predefined lifecycles (e.g.,
default,clean,site) that consist of phases (e.g.,validate,compile,test,package,install,deploy). Executing a phase triggers all preceding phases in that lifecycle. - Goals: Each plugin provides goals, which are specific tasks that can be executed. Goals are bound to lifecycle phases.
- Repositories: Locations where Maven artifacts (JARs, POMs) are stored. The default is Maven Central. You can configure local and remote repositories.
- Plugins: Extend Maven’s functionality. Common plugins include
maven-compiler-plugin,maven-surefire-plugin(for tests),maven-jar-plugin,maven-war-plugin.
Commands / Usage
Basic Build Execution
-
Clean and Build:
mvn clean installCleans the project (removes previous build artifacts) and then runs all phases up to
install(compiles, tests, packages, and installs the artifact in the local repository). -
Compile:
mvn compileCompiles the source code of the project.
-
Test:
mvn testRuns the unit tests.
-
Package:
mvn packageCompiles, tests, and packages the code into its distributable format (e.g., JAR, WAR).
-
Install:
mvn installInstalls the package into the local Maven repository, for use as a dependency in other local projects.
-
Deploy:
mvn deployDeploys the package to a remote repository, making it available for other developers and projects.
-
Clean:
mvn cleanDeletes the project’s build output directory (usually
target/).
Project Information and Generation
-
Generate Project Structure:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=falseCreates a new Maven project with a basic directory structure using a specified archetype.
-
Display Project Information:
mvn help:effective-pomDisplays the fully resolved POM, including parent POMs and plugin configurations.
-
List Available Goals:
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-compiler-pluginDescribes a specific plugin and its goals.
Dependency Management
-
Dependency Tree:
mvn dependency:treeDisplays the project’s dependency tree, showing direct and transitive dependencies. Useful for diagnosing conflicts.
-
Resolve Dependencies:
mvn dependency:resolveResolves project dependencies and lists them.
-
Analyze Dependencies:
mvn dependency:analyzeAnalyzes the project’s dependencies to identify unused declared dependencies and used but undeclared dependencies.
Running Applications
-
Run Main Class (if packaged as executable JAR):
mvn exec:java -Dexec.mainClass="com.mycompany.app.App"Executes the
mainmethod of a specified class. -
Run Application with Specific JAR:
mvn exec:java -Dexec.jar="/path/to/my-app.jar" -Dexec.mainClass="com.mycompany.app.App"Executes the
mainmethod of a specified class within a given JAR.
Plugin Execution
-
Run a Specific Plugin Goal:
mvn compiler:compileExecutes the
compilegoal of themaven-compiler-plugin. -
Run a Specific Plugin Goal with Parameters:
mvn surefire-report:report-only -Dsurefire.reportsdir=target/surefire-reportsExecutes the
report-onlygoal of themaven-surefire-report-plugin, specifying a directory for reports.
Profiles
-
Build with a Specific Profile:
mvn install -P productionActivates the
productionprofile during the build. -
Build with Multiple Profiles:
mvn install -P dev,testingActivates both
devandtestingprofiles.
Other Useful Flags
-
Skip Tests:
mvn install -DskipTestsSkips running tests during the build.
-
Offline Mode:
mvn install -oRuns Maven in offline mode. It will not attempt to connect to any network resources. Dependencies must be in the local repository.
-
Non-Recursive Build:
mvn install -NDo not recurse into sub-modules.
-
Show Version:
mvn -vDisplays the Maven version and Java version.
Common Patterns
-
Build a WAR file for a web application:
mvn clean package(Assumes
maven-war-pluginis configured inpom.xml) -
Run integration tests (requires
failsafeplugin setup):mvn verifyThe
verifyphase is typically used for integration tests. -
Check for code quality issues (e.g., with Checkstyle, PMD):
mvn verify site(Requires relevant plugins configured in
pom.xmlto run during theverifyorsitephases) -
Update dependencies in a project (forces re-download):
mvn clean install -UThe
-Uflag forces an update of the metadata and checksums for remote snapshots and releases. -
Build a specific module in a multi-module project:
cd my-module mvn installNavigate to the module’s directory and run the desired command. Maven will build only that module and its dependencies.
-
Executing a specific test class:
mvn test -Dtest=com.mycompany.app.MyTestClassRuns only the tests within
MyTestClass. -
Executing tests matching a pattern:
mvn test -Dtest=**/My*TestRuns all test classes whose names start with "My" and end with "Test".
Gotchas
- Transitive Dependency Conflicts: When multiple dependencies rely on different versions of the same transitive dependency, Maven might pick one, potentially leading to runtime errors. Use
mvn dependency:treeto identify conflicts and explicitly declare the desired version in yourpom.xmlusing the<dependencyManagement>section. - Snapshot Versions: Snapshot versions (
-SNAPSHOT) are dynamic and can change. Using-Uforces Maven to check for updated snapshots. Be cautious when deploying snapshot versions to remote repositories. - Plugin Prefix Resolution: Maven uses a prefix to map plugins (e.g.,
compilermaps toorg.apache.maven.plugins:maven-compiler-plugin). If a plugin isn’t found, ensure it’s correctly configured in thepom.xmlor that you’re using the full artifact ID. - Local Repository Location: Maven stores downloaded artifacts in a local repository, typically
~/.m2/repository. If this directory becomes corrupted or you need to clear it, manually deleting contents can resolve issues, but be aware it will force re-downloading everything. - Build Failure on First Run: Sometimes, especially with complex projects or network issues, the first build might fail. Running
mvn clean installagain often resolves transient problems. - Profile Activation: Profiles can be activated in several ways (
<activeByDefault>,-Pflag, OS settings, JDK version). Understanding how profiles are activated is crucial for consistent builds. mvn installvs.mvn deploy:installputs artifacts into your local repository, useful for local development.deploypushes artifacts to a remote repository, making them available to others. Don’t confuse their purposes.