Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Testing and Publishing

Publishing Libraries with Gradle: maven-publish and POM

Learn to publish a Java library with Gradle's maven-publish plugin: publications, POM metadata, sources and javadoc jars, repositories, credentials, signing and Maven Central basics.

Building a jar is only half the story. To let other teams, or the world, use your library, you must publish it to a repository along with metadata that describes its dependencies. In the Java world that means Maven coordinates (group:name:version) and a pom.xml, even when you build with Gradle.

This lesson walks through the maven-publish plugin: defining a publication, filling in the POM, choosing a repository, handling credentials safely, signing artifacts and the steps for Maven Central. It builds on the java-library plugin.

Gradle cannot run on this site, and publishing needs real repositories. The build code is read-only. The Java stand-ins generate a POM and a repository layout on Piston.

Coordinates

Every published artifact has three identifying parts:

Part Gradle property Example
Group group com.example.shop
Name (artifactId) rootProject.name or artifactId in publication shop-core
Version version 1.4.0

Set group and version in the build script (or in gradle.properties):

Kotlin
group = "com.example.shop"
version = "1.4.0"

A first publication

Kotlin
plugins {
    `java-library`
    `maven-publish`
}

java {
    withSourcesJar()
    withJavadocJar()
}

publishing {
    publications {
        create<MavenPublication>("mavenJava") {
            from(components["java"])
            artifactId = "shop-core"

            pom {
                name = "Shop Core"
                description = "Pricing and cart logic for the shop."
                url = "https://github.com/example/shop"
                licenses {
                    license {
                        name = "The Apache License, Version 2.0"
                        url = "https://www.apache.org/licenses/LICENSE-2.0.txt"
                    }
                }
                developers {
                    developer {
                        id = "ada"
                        name = "Ada Example"
                    }
                }
                scm {
                    connection = "scm:git:https://github.com/example/shop.git"
                    url = "https://github.com/example/shop"
                }
            }
        }
    }

    repositories {
        maven {
            name = "local"
            url = uri(layout.buildDirectory.dir("repo"))
        }
    }
}

Key points:

  • from(components["java"]) publishes the main jar plus the dependency information. With withSourcesJar() and withJavadocJar() it also publishes -sources.jar and -javadoc.jar, which IDEs and Maven Central expect.
  • The pom {} block fills the pom.xml. Maven Central requires name, description, URL, license, developers and SCM.
  • The dependency scopes in the POM are derived automatically: api becomes compile scope, implementation becomes runtime.

Publishing tasks

The plugin generates tasks named after publications and repositories:

TEXT
./gradlew publishToMavenLocal                     # to ~/.m2/repository
./gradlew publishMavenJavaPublicationToLocalRepository   # to build/repo
./gradlew publish                                 # all publications to all repositories
./gradlew generatePomFileForMavenJavaPublication  # inspect build/publications/mavenJava/pom-default.xml

publishToMavenLocal is handy for testing a library in another project on your machine. Remember to add mavenLocal() to the consumer's repositories, and remove it afterwards because it hides what is really available online.

Remote repositories and credentials

Kotlin
publishing {
    repositories {
        maven {
            name = "company"
            url = uri("https://repo.company.example/releases")
            credentials {
                username = providers.gradleProperty("repoUser").orNull
                password = providers.gradleProperty("repoPassword").orNull
            }
        }
    }
}

Never put passwords in the build file. Read them from ~/.gradle/gradle.properties (outside version control) or from environment variables in CI (ORG_GRADLE_PROJECT_repoUser, ORG_GRADLE_PROJECT_repoPassword). A common pattern uses a snapshot repository for versions ending in -SNAPSHOT and a release repository otherwise:

Kotlin
url = uri(if (version.toString().endsWith("SNAPSHOT")) snapshotsUrl else releasesUrl)

Signing

Maven Central requires GPG signatures. The core signing plugin handles it:

Kotlin
plugins { signing }

signing {
    val key = providers.environmentVariable("SIGNING_KEY").orNull
    val pass = providers.environmentVariable("SIGNING_PASSWORD").orNull
    useInMemoryPgpKeys(key, pass)
    sign(publishing.publications["mavenJava"])
}

Keep the private key in CI secrets, not in the repository.

Publishing to Maven Central

Central uses a Central Portal with a publishing API. The checklist: verify your namespace (domain or GitHub-based group), provide the complete POM, sources and javadoc jars, sign everything, and upload through the portal or a community plugin that talks to its API. Because the details change over time, follow the portal's current documentation for the final step; the Gradle part (publication, POM, signing) is as above.

Stand-in: a POM and repository layout

A Maven repository is just files laid out by coordinates. This program generates the path and a minimal POM for a coordinate, like generatePomFileForMavenJavaPublication.

Java Stand-in: repository layout and POM (not Gradle)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Gradle Module Metadata

Besides the POM, Gradle publishes a .module file with richer information: variants, capabilities and platform constraints. Gradle consumers use it automatically; Maven consumers ignore it and use the POM. You rarely need to touch it, except to disable it with tasks.withType<GenerateModuleMetadata> { enabled = false } if a downstream tool misbehaves.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does from(components["java"]) in a publication do?

    The java component bundles the main jar, optional sources and javadoc jars and the dependency data used to write the POM.
  2. 2. Which command installs a library into ~/.m2/repository for testing in another local project?

    publishToMavenLocal is provided by maven-publish and writes to the local Maven repository.
  3. 3. How should repository passwords be supplied?

    Secrets must stay out of version control. Gradle properties and CI environment variables keep them separate.
  4. 4. In the generated POM, an api dependency appears with which scope?

    api dependencies are needed at compile time by consumers, so they map to compile scope; implementation maps to runtime.

Summary

  • Publish with maven-publish: define a MavenPublication from components["java"].
  • Fill the POM (name, description, URL, license, developers, SCM), and add sources and javadoc jars.
  • publishToMavenLocal is for local testing; publish pushes to configured repositories.
  • Keep credentials and signing keys out of the repository.
  • Central needs a verified namespace, complete POM and signatures.

Next: Versioning, fat jars and distributions