Java Multi-Module Projects
In this page:
What is a Multi-Module Project?
A multi-module project groups several related sub-projects, such as an API layer, a service layer, and a web layer, under a single parent project, letting them share configuration and be built together as one unit.
Example: What is a Multi-Module Project?
public class Main {
public static void main(String[] args) {
String[] modules = {"api", "service", "web"}; // share config, built together
for (String m : modules) System.out.println(m);
}
}
Login to try C/C++/Java/PHP code in the editor
Parent POM Structure
In Maven, the parent module has packaging type pom rather than jar, since it exists only to declare shared properties, dependency versions, and plugin configuration that every child module inherits.
Example: Parent POM Structure
public class Main {
public static void main(String[] args) {
String parentPom = "<packaging>pom</packaging>"; // declares shared config only, not a jar itself
System.out.println(parentPom);
}
}
Login to try C/C++/Java/PHP code in the editor
Module Dependencies
Modules within the same multi-module project can depend on each other exactly like external libraries, using the same groupId, artifactId, and version coordinates, letting the build system track the correct build order automatically.
Example: Module Dependencies
public class Main {
public static void main(String[] args) {
String moduleDependency = "<groupId>com.example</groupId>\n<artifactId>api</artifactId>\n<version>1.0</version>";
System.out.println(moduleDependency); // same coordinates as an external library
}
}
Login to try C/C++/Java/PHP code in the editor
Building All Modules Together
Running a build command from the parent project's root builds every module in the correct dependency order, while flags like -pl and -am let you target a specific module and its dependencies without rebuilding the entire project.
Example: Building All Modules Together
public class Main {
public static void main(String[] args) {
String buildAll = "mvn install"; // builds every module in dependency order
String buildOne = "mvn install -pl service -am"; // targets one module plus its dependencies
System.out.println(buildAll + " / " + buildOne);
}
}
Login to try C/C++/Java/PHP code in the editor
Gradle Multi-Project Builds
Gradle multi-project builds are configured through a settings.gradle file that lists every sub-project, and one sub-project can depend on another using Gradle's project() function instead of full external dependency coordinates.
Example: Gradle Multi-Project Builds
public class Main {
public static void main(String[] args) {
String settingsGradle = "include 'api', 'service', 'web'";
String dependency = "implementation project(':api')"; // internal, not external coordinates
System.out.println(settingsGradle + " / " + dependency);
}
}
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: