Search code examples
javagradlelibraries

How do I add libraries to my Gradle file?


It's probably very simple, but only to people who know what they are doing. I have a Java program that imports these two:

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;

As an aside, I don't want to use the lang3 package but the lang package.

I do not have anything in my Gradle file about these. When I try to build the file, it gives me errors for these two, saying the packages do not exist.

My questions are:

  • Do I need to add them as "compile" or as "api"?
  • What is the exact syntax? I have lines that look like this: api group: 'commons-httpclient', name: 'commons-httpclient', version: '3.1'
  • How do I find the right name (or should I just invent one)? and the version?

Solution

  • Anything your code needs (besides basic JRE classes) is a dependency for your code. Gradle manages these dependencies, usually downloading them from a repository.

    First you need to find such a repository. You probably have repositories already configured in your build.gradle, like so:

    buildscript {
        repositories {
            mavenCentral()
            // maybe more repositories
        }
    }
    

    That means Gradle will try to download dependencies from Maven Central. You can either do a web search for "gradle" and your dependency, or go to repository and search, or check the dependency's homepage.

    You'll end up with a dependency name and version like 'org.apache.commons:commons-lang3:3.12.0'. This needs to go in your build.gradle.

    Gradle has different dependencies:

    • buildscript dependencies provide code that Gradle needs to execute to build your project, e.g., a tool to pull in version control system information or generate code

    • implementation dependencies are dependencies your code needs to run, like a logging framework or JSON parser or PDF generator

    • test dependencies are dependencies needed to run your automated tests, like JUnit

    Depending on where you need the dependency, you put it in the buildscript or the dependencies block.

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'org.tmatesoft.svnkit:svnkit:1.9.+'
        }
    }
    
    dependencies {
        implementation 'pdfbox:pdfbox:0.7.3'
        testImplementation 'junit:junit:4.+'
    }
    

    You don't need to repeat the implementation dependencies for the testImplementation btw, as it inherits them automatically.

    You can define your own configurations as need; see the Gradle manual on dependencies, for example if you have different test suites (unit, integration, performance, ...) that need different dependencies.