Sub topic 7
Where Dependencies Come From: Repositories and the Local Cache
Your project will often use code that other people wrote, such as JUnit for testing. A dependency is a library your project needs in order to compile, run, or test. When you list a dependency, Maven or Gradle finds the file and downloads it for you. This chapter explains where those files live and how the tools fetch them.
What a Repository Is
A repository is a storage place for built libraries. It holds JAR files plus small description files that list what each library needs. Every library sits in a folder path built from its coordinates.
The dots in the groupId turn into folders. Then come the artifactId and the version. For JUnit 5.10.2 the path looks like this:
org/junit/jupiter/junit-jupiter/5.10.2/junit-jupiter-5.10.2.jarBecause the coordinates map to one exact path, a build tool can always find the file it needs.
Maven Central
Maven Central is the largest public repository for Java libraries. It is free, and most open-source Java projects publish there. You can search it at https://central.sonatype.com.
The two tools reach Central in different ways:
| Tool | Uses Maven Central by default? | What you write |
|---|---|---|
| Maven | Yes | Nothing extra |
| Gradle | No | `repositories { mavenCentral() }` |
Companies often run their own private repository for in-house libraries. Both tools can use more than one repository.
The Local Cache
Downloading the same file on every build would be slow. So each tool keeps a local cache: a folder on your computer that stores every file it has already downloaded.
- Maven keeps its cache in
~/.m2/repository. This folder is also called the local repository. - Gradle keeps its cache in
~/.gradle/caches.
Before it goes to the internet, the tool checks the cache. If the file is there, it uses it right away. If not, it downloads the file and saves a copy.
Looking Inside the Cache
After you build a project that uses JUnit, you can see the cached files. Run these commands in a terminal on macOS or Linux:
ls ~/.m2/repository/org/junit/jupiter/junit-jupiter/5.10.2/
ls ~/.gradle/caches/modules-2/files-2.1/org.junit.jupiter/junit-jupiter/The first command lists the JAR file and its .pom file in the Maven cache. The second shows the version folders in the Gradle cache.
Exercise
You build a Gradle project on a new laptop, and it fails with "Could not find org.junit.jupiter:junit-jupiter:5.10.2". The same dependency works in Maven. What is the most likely cause?
Show answer
The build.gradle.kts file does not have a repositories block with mavenCentral(). Maven uses Maven Central by default, but Gradle only searches repositories you list.
Exercise
Your second build is much faster than the first, even though you changed nothing. Why?
Show answer
The first build downloaded the dependencies into the local cache. The second build found them there and did not need to download them again.