Local JAR Files as Gradle Dependencies – 本地JAR文件作为Gradle的依赖项

最后修改: 2021年 6月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将重点讨论如何将本地JAR文件添加到我们的Gradle依赖中。

2. Local JARs

2.本地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.

在我们开始解释向 Gradle 添加本地 JAR 文件的过程之前,最好先提一下,不建议手动添加公共资源库中的依赖。像Gradle这样的构建系统之所以存在,最重要的原因之一就是要自动完成这种事情。在Gradle之前,我们曾经下载JAR文件并将其放入libs文件夹。现在Gradle为我们自动处理这些事情。

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

然而,这个过程仍然支持Gradle的特殊用途,如自定义JAR文件。

3. Flat Directory

3.扁平化目录

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

如果我们想使用一个平面文件系统目录作为我们的仓库,我们需要在build.gradle文件中添加以下内容。

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:

这使得Gradle寻找lib1lib2的依赖。一旦我们设置了平坦的目录,我们就可以从lib1lib2文件夹中使用我们的本地JAR文件。

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

4. File Collections

4.文件收藏

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

平板目录的另一种方法是直接提到文件,而不使用flatdir:

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

5. File Tree

5.文件树

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:

我们可以告诉Gradle在某个目录下寻找所有的JAR文件,而不缩小名字的范围。如果我们不能或不想把某些文件放在资源库中,这可能很有用。但我们必须小心对待这个问题,因为它也可能添加不需要的依赖。

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

6. Using IntelliJ

6.使用IntelliJ

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

还有一种方法可以利用本地jar文件。首先,我们进入项目结构

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

然后我们点击列表上方的加号按钮,选择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.

然后一个对话窗口要求我们找到JAR文件。选择之后,我们可以点击确定,我们的项目就可以访问存档中的方法和类。

7. Conclusion

7.结语

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.

在这篇文章中,我们研究了利用JAR文件的各种方法,这些文件并不托管在Gradle项目的标准仓库中。