Composite builds
A multi-project build has one settings file. A composite build has several: a build can include another build, and a dependency on a coordinate of that build is then resolved from its sources, not from a repository. It is how a library and the program that uses it are developed together without publishing anything.
Two builds, two settings files
lib/settings.gradle
rootProject.name = 'colors'
lib/build.gradle
plugins {
id 'java-library'
}
group = 'com.example'
version = '1.0.0'
lib/src/main/java/com/example/Colors.java
package com.example;
public final class Colors {
public static String red() {
return "#e53935";
}
}
app/settings.gradle
rootProject.name = 'palette'
includeBuild('../lib')
app/build.gradle
plugins {
id 'java'
id 'application'
}
dependencies {
implementation 'com.example:colors:1.0.0'
}
application {
mainClass = 'com.example.Show'
}
app/src/main/java/com/example/Show.java
package com.example;
public final class Show {
public static void main(String[] args) {
System.out.println("red is " + Colors.red());
}
}
includeBuild
One line of the settings file is the whole mechanism, and it does not name a coordinate: Gradle reads the settings of the included build, learns that colors publishes com.example:colors:1.0.0, and substitutes that coordinate wherever a build script asks for it. No repositories block is needed in app for it, and no publication has to run first.
A coordinate of the included build that does not exist fails like any other missing dependency, which is the rule to remember when the substitution seems not to happen: the group and the version must be the ones the included build declares.
The dependency comes from source
cd app
gradle run --console=plain --offline --no-daemon
> Task :processResources NO-SOURCE
> Task :lib:compileJava
> Task :lib:processResources NO-SOURCE
> Task :lib:classes
> Task :lib:jar
> Task :compileJava
> Task :classes
> Task :run
red is #e53935
BUILD SUCCESSFUL in 18s
4 actionable tasks: 4 executed
The task names carry the build they belong to: :lib:compileJava is a task of the included build, and :compileJava is a task of the one being built. Edit Colors.java and the next gradle run of app recompiles the library first, because the sources are in the same build graph.
Related
- Multi-project builds: several projects with one settings file, which is the simpler form.
- Publish to mavenLocal: the other way to share a library between two builds.
- Build and configuration caching: what a composite build shares with the build that includes it.
Article author: Arthur Isaev