Publish to mavenLocal and use the jar

Two projects that are not in one build still share code through a repository. The maven-publish plugin writes a jar and a pom into ~/.m2/repository, and a second project that declares mavenLocal() depends on the same coordinates. Both folders are below, and both commands run.

The library

lib/settings.gradle

rootProject.name = 'wordcount'

lib/build.gradle

plugins { id 'java-library' id 'maven-publish' } group = 'com.example' version = '1.0.0' publishing { publications { library(MavenPublication) { from components.java } } }

lib/src/main/java/com/example/Words.java

package com.example; public final class Words { public static int count(String text) { return text.isBlank() ? 0 : text.trim().split("\\s+").length; } }

group and version are the coordinates the publication writes: the artifact id comes from the project name, wordcount. The from components.java line is what makes the plugin write a jar and a pom that lists the dependencies of the library, instead of a file somebody named by hand.

Publishing it

cd lib

gradle publishToMavenLocal --console=plain --offline --no-daemon

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :jar
> Task :generateMetadataFileForLibraryPublication
> Task :generatePomFileForLibraryPublication
> Task :publishLibraryPublicationToMavenLocal
> Task :publishToMavenLocal

BUILD SUCCESSFUL in 16s
5 actionable tasks: 5 executed

The files it wrote

ls ~/.m2/repository/com/example/wordcount/1.0.0

wordcount-1.0.0.jar
wordcount-1.0.0.module
wordcount-1.0.0.pom

The jar, the pom and a .module file. The module file is Gradle’s own metadata: it names the variants of the publication, so another Gradle build sees which dependencies belong to the API and which to the runtime. Maven reads the pom and ignores the module file, which is why the pom is written too.

A second project

app/settings.gradle

rootProject.name = 'report'

app/build.gradle

plugins { id 'java' id 'application' } repositories { mavenLocal() } dependencies { implementation 'com.example:wordcount:1.0.0' } application { mainClass = 'com.example.Report' }

app/src/main/java/com/example/Report.java

package com.example; public final class Report { public static void main(String[] args) { System.out.println("words: " + Words.count("a course about Gradle")); } }

The program runs

cd ../app

gradle run --console=plain --offline --no-daemon

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :run
words: 4

BUILD SUCCESSFUL in 17s
2 actionable tasks: 2 executed

Nothing links the two folders. The contract is the coordinate com.example:wordcount:1.0.0 and the repository they share, which is the same contract a library from Maven Central uses. The local repository is the shortest version of it, and the one repository every machine with Maven already has.

Related

Автор статьи: Arthur Isaev