Java Maven Basics
In this page:
What is Maven?
Maven is a build automation and dependency management tool for Java projects, using a declarative XML file called pom.xml to describe what a project needs, how to build it, and which external libraries it depends on.
Example: What is Maven?
public class Main {
public static void main(String[] args) {
// pom.xml declares what the project needs, how to build it, and its dependencies
System.out.println("Maven manages builds and dependencies declaratively via pom.xml");
}
}
Login to try C/C++/Java/PHP code in the editor
The pom.xml File
The pom.xml file, short for Project Object Model, is the heart of every Maven project, declaring its unique coordinates (groupId, artifactId, version), its packaging type, its dependencies, and any custom build configuration.
Example: The pom.xml File
public class Main {
public static void main(String[] args) {
String pomSnippet = "<groupId>com.example</groupId>\n<artifactId>app</artifactId>\n<version>1.0</version>";
System.out.println(pomSnippet); // unique coordinates declared in pom.xml
}
}
Login to try C/C++/Java/PHP code in the editor
Maven Build Lifecycle
Maven's default build lifecycle is a fixed sequence of phases -- validate, compile, test, package, verify, install, and deploy -- and running any phase automatically runs every phase before it in that sequence first.
Example: Maven Build Lifecycle
public class Main {
public static void main(String[] args) {
String[] phases = {"validate", "compile", "test", "package", "verify", "install", "deploy"};
for (String phase : phases) System.out.println(phase); // running one runs every phase before it too
}
}
Login to try C/C++/Java/PHP code in the editor
Adding Dependencies
Dependencies are declared inside the dependencies element of pom.xml, and Maven automatically downloads them, along with any of their own dependencies (called transitive dependencies), from a central repository.
Example: Adding Dependencies
public class Main {
public static void main(String[] args) {
String dependency = "<dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n</dependency>";
System.out.println(dependency); // Maven also downloads its transitive dependencies automatically
}
}
Login to try C/C++/Java/PHP code in the editor
Running Maven Commands
Common Maven commands include mvn compile to build source code, mvn test to run tests, mvn package to produce a distributable artifact, and mvn clean to remove previous build output before starting fresh.
Example: Running Maven Commands
public class Main {
public static void main(String[] args) {
String[] commands = {"mvn compile", "mvn test", "mvn package", "mvn clean"};
for (String cmd : commands) System.out.println(cmd);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: