'Optional Gradle dependencies for Maven libraries
I'm working on an Android library and would like to use a dependency only if the project using my library includes that dependency as well. Similar to what Picasso does with OkHttp.
I already took care of this on the main code by checking for ClassNotFoundExceptions but it still includes the dependencies upon deploying it to Maven Central. How do I generate something such as Maven's <optional>true</optional> tag?
I'm using gradle-mvn-push to deploy my artifacts via Gradle.
Solution 1:[1]
The Nebula Extra Configurations Gradle plugin seems to be providing optional.
You would use it like this:
apply plugin: 'java'
apply plugin: 'nebula.optional-base'
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.commons:commons-lang3:3.3.2', optional
compile group: 'log4j', name: 'log4j', version: '1.2.17', optional
}
Solution 2:[2]
According to this blog, Compile-only dependencies address a number of use cases, including:
- Dependencies required at compile time but required at runtime only when using certain features, a.k.a. optional dependencies;
- Dependencies required at compile time but never required at runtime, such as source-only annotations or annotation processors;
- Dependencies whose API is required at compile time but whose implementation is to be provided by a consuming library, application or runtime environment.
So just using compileOnly to declare an optional dependency.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gimix |
| Solution 2 | Yuri |
