Build Tools (Maven)

Learn how to manage dependencies and build your Java projects using Apache Maven.

Apache Maven

Maven is a powerful project management tool that is based on POM (Project Object Model). It is used for project builds, dependency management, and documentation.

Why use Maven?

  • Dependency Management: Automatically downloads libraries and their dependencies.
  • Standard Project Structure: Provides a consistent directory structure.
  • Build Lifecycle: Standardized build process (compile, test, package, deploy).

The pom.xml File

The pom.xml file is the core of a Maven project. It contains configuration information about the project and details used by Maven to build it.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
</project>

Dependency Scopes

  • compile: Default scope. Available in all classpaths.
  • provided: Expects JDK or container to provide it (e.g., Servlet API).
  • runtime: Required for execution, not compilation (e.g., JDBC driver).
  • test: Only required for compiling and running tests (e.g., JUnit).

Maven Lifecycle

  1. validate: Validate the project is correct.
  2. compile: Compile the source code.
  3. test: Test the compiled source code.
  4. package: Take the compiled code and package it (JAR/WAR).
  5. verify: Run checks on results of integration tests.
  6. install: Install the package into the local repository.
  7. deploy: Copies the final package to the remote repository.

Tip 💡

Maven repositories like Maven Central host millions of libraries that you can easily include in your project.