0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · Урок

Публикация в репозитории

Публикуйте артефакты проекта в репозиториях Maven Central, Artifactory или Nexus.

«Публикация в репозитории» — бесплатный урок Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Groovy & Gradle: JVM Automation and Build Engineering, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Welcome to Publishing!

Ever wondered how open-source libraries or internal company tools become available for others to use? It's all about publishing!

In this lesson, you'll learn how to use Gradle to publish your project's compiled artifacts (like JARs) to central repositories. This makes them easily consumable as dependencies by other projects.

Artifacts & Repositories

Let's clarify some key terms:

  • An artifact is a deployable output of your project, typically a compiled JAR, WAR, or AAR file. It's the 'product' you want to share.
  • A repository is a storage location for these artifacts. Think of it as a digital library where artifacts are stored and retrieved. Examples include Maven Central, JCenter, Artifactory, or Nexus.

They are crucial for managing project dependencies.

The Maven Publish Plugin

Gradle uses plugins to extend its core functionality. For publishing artifacts to Maven-compatible repositories, we use the maven-publish plugin.

This powerful plugin provides the necessary tasks and a Domain Specific Language (DSL) to configure exactly what and where you want to publish.

Applying the Plugin

The first step is to apply the maven-publish plugin in your build.gradle file. We typically also apply the java plugin if we're publishing a Java library.

Don't forget to define your project's group and version, as these are critical metadata for your published artifact!

plugins {
    id 'java'
    id 'maven-publish'
}

group = 'com.coddykit.mylib'
version = '1.0.0'

// Minimal task to compile Java for publishing
java {
    withSourcesJar()
    withJavadocJar()
}

Defining a Publication

Inside the publishing block, you define one or more publications. Each publication specifies what artifacts (e.g., your main JAR, source JAR, Javadoc JAR) will be part of that release.

The from components.java line tells Gradle to include all the standard Java component artifacts (like the compiled JAR) in this publication.

plugins {
    id 'java'
    id 'maven-publish'
}

group = 'com.coddykit.mylib'
version = '1.0.0'

java {
    withSourcesJar()
    withJavadocJar()
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            groupId = project.group
            artifactId = 'my-awesome-lib'
            version = project.version

            from components.java // Includes the main JAR
        }
    }
}

Adding Sources & Javadoc

It's good practice to publish your project's source code and Javadoc documentation along with the compiled JAR. This helps consumers understand and debug your library.

The java plugin's withSourcesJar() and withJavadocJar() methods simplify creating these additional artifacts.

plugins {
    id 'java'
    id 'maven-publish'
}

group = 'com.coddykit.mylib'
version = '1.0.0'

java {
    withSourcesJar()
    withJavadocJar()
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            groupId = project.group
            artifactId = 'my-awesome-lib'
            version = project.version

            from components.java
            artifact sourcesJar // Add sources JAR
            artifact javadocJar // Add Javadoc JAR
        }
    }
}

// These tasks are automatically created by withSourcesJar()/withJavadocJar()
// but shown here for clarity if you need custom configuration.
// task sourcesJar(type: Jar) { from sourceSets.main.allSource archiveClassifier.set('sources') }
// task javadocJar(type: Jar) { from javadoc.destinationDir archiveClassifier.set('javadoc') }

Configuring Repositories

Now you need to tell Gradle *where* to publish your artifacts. This is done in the repositories block within publishing.

You can define multiple target repositories, including local ones for testing or remote ones like your company's Artifactory/Nexus instance.

plugins {
    id 'java'
    id 'maven-publish'
}

group = 'com.coddykit.mylib'
version = '1.0.0'

java { withSourcesJar(); withJavadocJar() }

publishing {
    publications {
        mavenJava(MavenPublication) { /* ... */ }
    }
    repositories {
        mavenLocal() // Publishes to your local Maven cache (~/.m2/repository)
        maven {
            name = "myCompanyRepo"
            url = uri("https://mycompany.com/maven-repo")
            // Credentials will be added here
        }
    }
}

Secure Credentials

For remote repositories, you'll almost always need authentication. It's vital to handle credentials securely and avoid hardcoding them directly in your build.gradle file.

  • Environment Variables: Use System.getenv('VAR_NAME') to read from system environment variables.
  • Project Properties: Access properties via project.properties['propName'], which can be set in gradle.properties or passed via command line (-PpropName=value).
plugins { id 'java'; id 'maven-publish' }
group = 'com.coddykit.mylib'; version = '1.0.0'
java { withSourcesJar(); withJavadocJar() }
publishing {
    publications { mavenJava(MavenPublication) { /* ... */ } }
    repositories {
        maven {
            name = "myCompanyRepo"
            url = uri("https://mycompany.com/maven-repo")
            credentials {
                // Securely retrieve username and password
                username = project.properties['repoUser'] ?: System.getenv('REPO_USER')
                password = project.properties['repoPass'] ?: System.getenv('REPO_PASS')
            }
        }
    }
}

Executing the Publish Task

Once your build.gradle is configured, Gradle automatically generates publishing tasks. The main task is publish, which publishes all defined publications to all configured repositories.

You can also target specific publications or repositories, e.g., publishMavenJavaPublicationToMyCompanyRepo.

# To publish all configured publications to all repositories:
gradle publish

# To publish a specific publication to a specific repository:
gradle publishMavenJavaPublicationToMyCompanyRepo

Publishing Quiz

You are configuring a build.gradle file to publish a Java library to a remote repository named "MyCompanyRepo".

Recap: Publish with Gradle

Fantastic work! You've successfully navigated the essentials of publishing artifacts with Gradle.

You now know how to:

  • Apply the maven-publish plugin.
  • Define what artifacts to publish using a MavenPublication.
  • Configure target repositories, including secure authentication.
  • Execute Gradle publish tasks to share your project's outputs.

This skill is fundamental for creating reusable libraries and integrating with CI/CD pipelines!

Часто задаваемые вопросы

Урок «Публикация в репозитории» бесплатный?

Да — полный текст урока «Публикация в репозитории» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Groovy & Gradle: JVM Automation and Build Engineering, подпишись на CoddyKit PRO. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Чему я научусь в уроке «Публикация в репозитории»?

Публикуйте артефакты проекта в репозиториях Maven Central, Artifactory или Nexus. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Groovy & Gradle: JVM Automation and Build Engineering?

Предыдущий опыт не требуется. Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Публикация в репозитории»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Groovy & Gradle: JVM Automation and Build Engineering?

Да. Каждый урок Groovy & Gradle: JVM Automation and Build Engineering включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Упаковка JAR, WAR и EAR
  2. Публикация в репозитории
  3. Интеграция с CI/CD
  4. Версионирование и автоматизация релизов
← Назад к Groovy & Gradle: JVM Automation and Build Engineering