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

Зависимости между проектами

Управляйте зависимостями между подпроектами и обеспечивайте правильный порядок сборки и разрешение артефактов.

«Зависимости между проектами» — бесплатный урок 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 уроков всего.

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

Introduction to Project Dependencies

In a multi-project Gradle build, different subprojects often need to work together. One subproject might produce a library that another subproject uses.

This is where inter-project dependencies come in! They define how subprojects rely on each other, ensuring the correct build order and artifact sharing.

  • Inter-project dependencies: How one subproject uses code or outputs from another subproject.
  • Crucial for modular applications.

Declaring a Basic Dependency

Declaring that one subproject depends on another is straightforward in Gradle. You use the project() function within your dependencies block.

For example, if your app subproject needs code from your lib subproject, you'd add this to app/build.gradle:

// app/build.gradle
dependencies {
    implementation project(':lib')
}

The :lib part refers to the path of the lib subproject relative to the root.

Setting Up Our Example

Let's imagine a simple multi-project setup. We'll have a root project, an app subproject, and a lib subproject.

Your settings.gradle would look like this:

// settings.gradle
rootProject.name = 'my-multi-project'
include 'app', 'lib'

This tells Gradle about our two subprojects, app and lib.

`implementation` vs. `api`

When declaring inter-project dependencies, you'll typically use configurations like implementation or api.

  • implementation: The most common choice. The dependency is used internally by the subproject and is not exposed to consumers of that subproject.
  • api: Exposes the dependency to consumers. If app depends on lib via api, and otherApp depends on app, then otherApp will also see lib's API.

For internal use between subprojects, implementation is generally preferred for better encapsulation and faster builds.

The Library Subproject (`lib`)

First, let's create a simple class in our lib subproject that the app subproject will use. This class will provide a basic utility.

Inside lib/src/main/groovy/com/coddykit/LibUtils.groovy:

package com.coddykit

class LibUtils {
    static String getGreeting() {
        return "Hello from LibUtils!"
    }
}

App Subproject Using `lib`'s Code

Now, let's make our app subproject use the LibUtils class from our lib subproject. Remember, we declared implementation project(':lib') in app/build.gradle.

Try running this example:

package com.coddykit

import com.coddykit.LibUtils

class AppMain {
    static void main(String[] args) {
        String message = LibUtils.getGreeting()
        System.out.println(message)
    }
}

Automatic Build Order

One of the biggest advantages of declaring inter-project dependencies is that Gradle automatically figures out the correct build order.

  • If app depends on lib, Gradle ensures that lib is compiled and its artifacts are available before app starts its compilation.
  • This saves you from manually managing build sequences, especially in complex multi-project setups.

When you run gradle build from the root, Gradle will build lib first, then app.

Understanding Transitive Effects

What if your lib subproject itself depends on another subproject, say common?

// lib/build.gradle
dependencies {
    implementation project(':common')
}

// app/build.gradle
dependencies {
    implementation project(':lib')
}

If app depends on lib, and lib depends on common, Gradle will ensure that common is also built and its artifacts are available transitively to app's classpath for compilation, but not necessarily for its API if implementation is used for lib.

Maintain Clean Dependencies

To keep your multi-project builds manageable and efficient, follow these best practices:

  • Minimal Dependencies: Only declare dependencies on subprojects you truly need.
  • Use implementation: Prefer implementation over api for internal subproject dependencies to improve encapsulation and reduce rebuilds.
  • Clear Boundaries: Design your subprojects with clear responsibilities to avoid circular dependencies.
  • Avoid Deep Paths: Keep subproject paths concise (e.g., :module:submodule is fine, but avoid excessively long paths).

Dependency Declaration Check

You have a multi-project build with a web subproject and a core subproject. The web subproject needs to use classes from the core subproject for its internal logic, but not expose core's API to any further consumers of web.

Inter-Project Dependencies Recap

Great job! In this lesson, you learned how to manage dependencies between subprojects in a Gradle multi-project build.

  • We covered how to declare dependencies using project(':subproject').
  • We discussed the importance of implementation for internal use.
  • You saw how Gradle automatically handles build order.
  • We explored best practices for clean dependency management.

Mastering inter-project dependencies is key to building large, modular applications efficiently with Gradle!

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

Урок «Зависимости между проектами» бесплатный?

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

Чему я научусь в уроке «Зависимости между проектами»?

Управляйте зависимостями между подпроектами и обеспечивайте правильный порядок сборки и разрешение артефактов. Ты практикуешь 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.

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

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

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

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

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

  1. Структура проекта монорепозитория
  2. Подпроекты и конфигурации
  3. Зависимости между проектами
  4. Композитные сборки и композиция сборок
← Назад к Groovy & Gradle: JVM Automation and Build Engineering