Sub topic 1
What a Build Tool Does for You
Why build tools exist
A build tool is a program that turns your source code into something you can run or share. It compiles code, runs tests, packages files, and downloads libraries. You could do each step yourself, but a build tool does them the same way every time, with one command.
Building by hand
Here is a small app at src/main/java/com/example/App.java:
package com.example;
public class App {
public static void main(String[] args) {
System.out.println(greeting("World"));
}
static String greeting(String name) {
return "Hello, " + name + "!";
}
}You can build it with the tools that come with the JDK:
mkdir -p out
javac -d out src/main/java/com/example/App.java
java -cp out com.example.App
jar --create --file app.jar --main-class com.example.App -C out .
java -jar app.jarjavac compiles the code. The classpath (-cp) is the list of places where Java looks for compiled classes. A JAR file is a zip file of classes. Once a project has many files and libraries, typing these commands by hand gets slow and error-prone.
The standard layout
Maven and Gradle expect the same folders:
| Folder | Contents |
|---|---|
| `src/main/java` | App code |
| `src/test/java` | Test code |
| `target` or `build` | Output that the tool creates |
Naming artifacts
An artifact is a file the build produces, such as a JAR. Each artifact gets three coordinates: groupId (your organization), artifactId (the project name), and version.
Your first pom.xml
A POM (Project Object Model) is Maven's settings file. Save it as pom.xml in the project root:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>hello</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>Lifecycles, phases, and goals
A lifecycle is the ordered list of steps in a build. Each step is a phase. When you run a phase, Maven also runs every phase before it. A goal is one small job that a plugin does inside a phase.
mvn compile
mvn package
java -cp target/hello-1.0-SNAPSHOT.jar com.example.App
mvn clean verifyExercise
You run mvn package. Which earlier phases also run?
Show answer
validate, compile, and test. Maven runs every phase before package, in order.
Exercise
What are the three coordinates in the pom.xml above?
Show answer
groupId com.example, artifactId hello, and version 1.0-SNAPSHOT.