How would you configure a Gradle project to publish artifacts to a remote repository?

Publishing artifacts from a Gradle project means packaging the build output and uploading it to a remote repository (Maven Central, an internal Nexus/Artifactory, or the Gradle Plugin Portal) so other projects can consume it as a dependency. This is done with the built-in maven-publish plugin.

Key Points: • Apply the maven-publish plugin, which adds publishing infrastructure to the build. • Define a publication in the publishing.publications block, specifying groupId, artifactId, version, and the component to publish (from(components.java)). • Declare the target repository's URL and credentials in the publishing.repositories block. • Running gradle publish uploads the artifact (and generated POM) to the configured repository. • Credentials should be supplied via environment variables or gradle.properties, never hardcoded in build.gradle.

Example: A shared internal library adds the maven-publish plugin, configures its publication with the java component, and points the repository block at an internal Artifactory instance, so gradle publish makes the library immediately consumable by other teams' projects.

Code Example:

plugins {
    id 'maven-publish'
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            groupId = 'com.example'
            artifactId = 'shared-lib'
            version = '1.2.0'
        }
    }
    repositories {
        maven {
            url = uri('https://artifactory.example.com/repo')
            credentials {
                username = System.getenv('REPO_USER')
                password = System.getenv('REPO_PASS')
            }
        }
    }
}

Interview Tip: A concise interview answer is:

"I apply the maven-publish plugin, define a publication that points at the java component with the right group, artifact, and version, and configure the target repository with credentials pulled from environment variables. Running gradle publish then uploads the artifact and its POM so other projects can depend on it."