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

Пользовательские репозитории и BOM

Настройте пользовательские репозитории Maven или Ivy и используйте спецификации Bill of Materials (BOM) для согласованных версий зависимостей.

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

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

Beyond Maven Central

By default, Gradle looks for dependencies in Maven Central. But what if your dependencies aren't there?

Custom repositories allow you to fetch libraries from other locations, like:

  • Your company's private artifact server.
  • Specific public repositories (e.g., Google's Maven repo for Android).
  • Local file system directories.

Adding a Maven Repository

To add a custom Maven repository, you declare it in the repositories block of your build.gradle file.

Gradle will check repositories in the order they are declared, stopping at the first match.

repositories {
    mavenCentral()
    maven {
        url 'https://repo.spring.io/milestone'
    }
}

Example: Google Maven Repo

Many Android libraries are hosted on Google's Maven repository. You'd add it like this:

This is crucial for projects using Google-specific libraries.

repositories {
    google() // Shortcut for Google's Maven repo
    mavenCentral()
}

Understanding Ivy Repositories

While Maven is very common, Gradle also supports Ivy repositories. Ivy has a more flexible layout for artifacts.

You might encounter Ivy repositories in older projects or specific corporate environments.

repositories {
    ivy {
        url "http://repo.mycompany.com/ivy"
        layout "pattern", {
            artifact "[organization]/[module]/[revision]/[artifact](-[classifier])-[revision].[ext]"
        }
    }
}

Local Directory as Repo

For testing or internal use, you can even use a local directory as a repository. This is handy for sharing artifacts within a team without a dedicated server.

Just specify the path to your local folder.

repositories {
    flatDir {
        dirs 'libs' // Looks for JARs directly in the 'libs' folder
    }
    // Or a more structured Maven-like local repo
    maven {
        url uri('../my-local-maven-repo')
    }
}

Bill of Materials (BOMs)

A Bill of Materials (BOM) is a special Maven POM file that defines a curated list of dependency versions.

It helps manage transitive dependencies and ensures consistent versions across a multi-module project or when using a suite of related libraries.

Consistency with BOMs

BOMs solve a common problem: dependency version conflicts. If multiple libraries depend on different versions of the same transitive dependency, you can end up with unpredictable behavior.

With a BOM, you declare a single "source of truth" for versions, making your build more reliable.

Importing a BOM

To use a BOM in Gradle, you declare it as a dependency using the platform() or enforcedPlatform() function. This tells Gradle to use the versions specified in the BOM.

Notice how we don't specify versions for spring-core or spring-web; the BOM handles it!

dependencies {
    implementation platform('org.springframework.boot:spring-boot-dependencies:2.7.5')

    // These versions are now managed by the BOM
    implementation 'org.springframework:spring-core'
    implementation 'org.springframework:spring-web'
}

Platform vs. EnforcedPlatform

There are two ways to import a BOM:

  • platform(): Suggests versions. Other modules can override these versions if explicitly declared.
  • enforcedPlatform(): Strictly enforces versions. Any explicitly declared versions for dependencies in the BOM will be overridden by the BOM's version.

Use enforcedPlatform() for strong version consistency.

Check Your Knowledge

Let's test your understanding of custom repositories and BOMs!

Custom Repos & BOMs Recap

Great job! You've learned how to:

  • Configure custom Maven and Ivy repositories in Gradle.
  • Understand the importance of repository order.
  • Use local directories as repositories.
  • Leverage Bill of Materials (BOMs) for consistent dependency version management.
  • Differentiate between platform() and enforcedPlatform().

These techniques are vital for managing complex dependency landscapes in real-world projects!

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

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

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

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

Настройте пользовательские репозитории Maven или Ivy и используйте спецификации Bill of Materials (BOM) для согласованных версий зависимостей. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

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

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

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

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

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

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

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

  1. Объявление зависимостей проекта
  2. Разрешение зависимостей и кэширование
  3. Пользовательские репозитории и BOM
  4. Разрешение конфликтов версий и ограничения зависимостей
← Назад к Groovy & Gradle: JVM Automation and Build Engineering