Apache Maven

Language: Java

Build/Dependency Management

Maven was created by the Apache Software Foundation to simplify Java project builds, dependency resolution, and lifecycle management. It standardizes the build process, encourages best practices, and integrates with continuous integration tools, making it a cornerstone in modern Java development.

Apache Maven is a powerful build automation and project management tool for Java and other JVM-based languages. It provides a uniform build system, dependency management, and a project object model (POM) to define project structure, plugins, and external libraries.

Installation

website: https://maven.apache.org/install.html
maven_setup: Download Maven, extract to a directory, and set environment variables (M2_HOME, PATH) to use 'mvn' command.

Usage

Maven uses the Project Object Model (POM) to manage project configuration, dependencies, build plugins, and tasks. It supports standard lifecycles: clean, compile, test, package, verify, install, and deploy.

Creating a new Maven project

mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Generates a basic Java project structure with POM and source folders.

Compiling a Maven project

mvn compile

Compiles source code and resolves dependencies defined in pom.xml.

Running tests

mvn test

Executes unit tests using configured testing framework (e.g., JUnit).

Packaging a project

mvn package

Compiles, runs tests, and packages the project into a JAR or WAR file as defined in the POM.

Installing to local repository

mvn install

Installs the built artifact into the local Maven repository (~/.m2/repository) for use by other projects.

Adding dependencies

<dependencies>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
  </dependency>
</dependencies>

Declares a dependency in pom.xml so Maven downloads and manages the library automatically.

Running custom plugins

mvn clean verify -Pproduction

Executes custom plugins and profiles for complex builds or environment-specific tasks.

Error Handling

DependencyResolutionException: Occurs when Maven cannot resolve a dependency. Check the groupId, artifactId, version, and repository availability.
PluginExecutionException: Occurs when a Maven plugin fails during execution. Verify plugin configuration and version compatibility.
BuildFailureException: Occurs if compilation, tests, or packaging fails. Review logs, fix code or configuration issues.

Best Practices

Keep POM files organized and modular using parent/child projects.

Use dependency management to handle versions consistently across modules.

Leverage Maven profiles to differentiate builds for dev, test, and production.

Use the Maven Central repository or private artifact repositories for dependencies.

Regularly update Maven plugins and dependencies to maintain compatibility.