Sub topic 2
Where Dependencies Come From: Repositories and the Local Cache
Repositories and the local cache
A dependency is a library your code uses but did not write. A repository is a server that stores libraries by their coordinates (groupId, artifactId, version). The biggest public one is Maven Central.
Maven and Gradle do not download a library every time you build. The first download goes into a local cache, which is a folder on your computer. Maven keeps it in ~/.m2/repository, and Gradle keeps it in ~/.gradle/caches. Later builds read the library from that folder.
Declaring dependencies and scopes in Maven
In Maven, you list each library inside <dependencies> in pom.xml. A scope says when the library is needed. Here, test means JUnit is used only to compile and run tests. It is left out of your app.
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>If you leave out <scope>, Maven uses compile, which means the library is needed everywhere.
Your first Gradle project
Gradle reads a build script, which is a file of code that describes the build. With the Kotlin DSL (a build language based on Kotlin), the file is named build.gradle.kts:
plugins {
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:33.2.1-jre")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
application {
mainClass = "com.example.App"
}
tasks.named<Test>("test") {
useJUnitPlatform()
}Gradle tasks and the task graph
A task is one unit of work, such as compiling the code or running the tests. Tasks depend on other tasks. Gradle puts them in order using a task graph, so build runs compiling and testing first. You can add your own task:
tasks.register("hello") {
group = "custom"
description = "Prints a greeting"
doLast {
println("Hello from Gradle")
}
}./gradlew tasks
./gradlew hello
./gradlew build
./gradlew runDependency configurations in Gradle
Gradle uses configurations to say when a library is needed. They do the same job as Maven scopes.
| Maven scope | Gradle configuration | Needed for |
|---|---|---|
| compile | implementation | Compiling and running the app |
| runtime | runtimeOnly | Running only |
| provided | compileOnly | Compiling only |
| test | testImplementation | Compiling and running tests |
To see which libraries your app will use when it runs, print the dependency tree:
./gradlew dependencies --configuration runtimeClasspathExercise
You add a mocking library that only your tests use. Which Maven scope and which Gradle configuration should you use?
Show answer
In Maven, use the test scope. In Gradle, use testImplementation. Either way, the library stays out of the app you ship.