Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

In this tutorial, we'll focus on how we can add local JAR files to our Gradle dependencies.

2. Local JARs

Before we begin explaining the process of adding local JAR files to Gradle, it's good to mention that it is not recommended to manually add the dependencies that are available in the public repositories. One of the most important reasons why build systems like Gradle exist is to do this sort of thing automatically. Before Gradle, we used to download the JAR file and put it in the libs folder. Now Gradle handles these things automatically for us.

However, this process is still supported with Gradle for special purposes like custom JAR files.

3. Flat Directory

If we want to use a flat filesystem directory as our repository, we need to add the following to our build.gradle file:

repositories {
    flatDir {
        dirs 'lib1', 'lib2'

This makes Gradle look into lib1 and lib2 for dependencies. Once we set the flat directories, we can use our local JAR file from the lib1 or lib2 folder:

dependencies { implementation name: 'sample-jar-0.8.7' }

4. File Collections

An alternative approach to flat directory would be to mention files directly without using the flatdir:

implementation files('libs/a.jar', 'libs/b.jar')

5. File Tree

We can tell Gradle to look for all JAR files in a certain directory without narrowing down the names. This can be useful if we cannot, or don't want to, place certain files in a repository. But we have to be careful with this one, because it might add unwanted dependencies too:

implementation fileTree(dir: 'libs', include: '*.jar')

6. Using IntelliJ

There is another way to make use of the local jar file. First, we go to Project Structure:

Then we click on the plus button on top of the list and select Java:

Then a dialogue window asks us to locate the JAR file. After selecting it, we can click on OK, and our project can access the methods and classes in the archive.

7. Conclusion

In this article, we looked at various ways of making use of JAR files that are not hosted in a standard repository within a Gradle project.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Inline Feedbacks
View all comments