Dependencias entre proyectos
Gestione las dependencias entre subproyectos y garantice el orden correcto de compilación y la resolución de artefactos.
Dependencias entre proyectos es una lección gratuita de Groovy & Gradle: JVM Automation and Build Engineering en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Groovy & Gradle: JVM Automation and Build Engineering, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Groovy & Gradle: JVM Automation and Build Engineering incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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. Ifappdepends onlibviaapi, andotherAppdepends onapp, thenotherAppwill also seelib'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
appdepends onlib, Gradle ensures thatlibis compiled and its artifacts are available beforeappstarts 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: Preferimplementationoverapifor 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:submoduleis 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
implementationfor 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!
Preguntas frecuentes
¿La lección «Dependencias entre proyectos» es gratis?
Sí — el texto completo de «Dependencias entre proyectos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Groovy & Gradle: JVM Automation and Build Engineering, actualiza a CoddyKit PRO. El curso de Groovy & Gradle: JVM Automation and Build Engineering incluye 4 lecciones en total.
¿Qué aprenderé en «Dependencias entre proyectos»?
Gestione las dependencias entre subproyectos y garantice el orden correcto de compilación y la resolución de artefactos. Practicas Groovy & Gradle: JVM Automation and Build Engineering con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Groovy & Gradle: JVM Automation and Build Engineering?
No se requiere experiencia previa. Groovy & Gradle: JVM Automation and Build Engineering en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Dependencias entre proyectos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Groovy & Gradle: JVM Automation and Build Engineering?
Sí. Cada lección de Groovy & Gradle: JVM Automation and Build Engineering incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Estructura de proyectos en un monorepo
- Subproyectos y configuraciones
- Dependencias entre proyectos
- Compilaciones compuestas y composición de compilaciones