Build Tools: Maven and Gradle
Build tools automate compilation, testing, packaging, and deployment.
Maven and Gradle are the most used in the Java ecosystem.
What You'll Learn
- Maven: POM, lifecycle, dependencies
- Gradle: build.gradle, tasks
- Dependency management
- Plugins and configuration
Maven
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
</plugin>
</plugins>
</build>
</project>
Maven Lifecycle
| Phase |
Description |
| mvn clean |
Removes target/ |
| mvn compile |
Compiles sources |
| mvn test |
Runs tests |
| mvn package |
Creates JAR/WAR |
| mvn install |
Installs to local repository |
| mvn deploy |
Deploys to remote repository |
Gradle
plugins {
id 'java'
id 'application'
}
group = 'com.example'
version = '1.0.0'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.guava:guava:32.1.2-jre'
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
application {
mainClass = 'com.example.Main'
}
tasks.named('test') {
useJUnitPlatform()
}
plugins {
java
application
}
group = "com.example"
version = "1.0.0"
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:32.1.2-jre")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
}
tasks.test {
useJUnitPlatform()
}
application {
mainClass.set("com.example.Main")
}
Maven vs Gradle Comparison
When to Choose
| Aspect |
Maven |
Gradle |
| Configuration |
XML (verbose) |
Groovy/Kotlin (concise) |
| Performance |
Good |
Better (incremental) |
| Flexibility |
Convention-based |
Very flexible |
| Learning curve |
Easy |
Medium |
| IDE Support |
Excellent |
Excellent |
# Maven
mvn clean install # Full build
mvn test # Tests only
mvn dependency:tree # Dependency tree
mvn package -DskipTests # Package without tests
# Gradle
gradle build # Full build
gradle test # Tests only
gradle dependencies # List dependencies
gradle build -x test # Build without tests
gradle tasks # List available tasks