Java Library Plugin

Author Avatar
Young Hug Apr 26, 2020

The Java Library plugin expands the capabilities of the Java plugin by providing specific knowledge about Java libraries. In particular, a Java library exposes an API to consumers (i.e., other projects using the Java or the Java Library plugin). All the source sets, tasks and configurations exposed by the Java plugin are implicitly available when using this plugin.

In a word, Java Library Plugin is a plugin to control the dependencies of java projects and is compatible with the java plugin.

Usage

To use the Java Library plugin, include the following in your build script:

1
2
3
plugins {
id 'java-library'
}

API Vs Implementation

The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.

API

Dependencies appearing in the api configurations will be transitively exposed to consumers of the library, and as such will appear on the compile classpath of consumers.

Therefore should be declared as an api dependency:

  • types used in super classes or interfaces
  • types used in public method parameters, including generic parameter types (where public is something that is visible to compilers. I.e. , public, protected and package private members in the Java world)
  • types used in public fields
  • public annotation types

Implementation

Dependencies found in the implementation configuration will, on the other hand, not be exposed to consumers, and therefore not leak into the consumers’ compile classpath.

Therefore should be declared as an implementation dependency:

  • types exclusively used in method bodies
  • types exclusively used in private members
  • types exclusively found in internal classes (future versions of Gradle will let you declare which packages belong to the public API)

The Java Library plugin configurations

The following graph describes the main configurations setup when the Java Library plugin is in use.

java library ignore deprecated main

  • The configurations in green are the ones a user should use to declare dependencies
  • The configurations in pink are the ones used when a component compiles, or runs against the library
  • The configurations in blue are internal to the component, for its own use
  • The configurations in white are configurations inherited from the Java plugin

And the next graph describes the test configurations setup:

java library ignore deprecated test

The relationship in the above graphs is composition instead of inheriting.

References

[1] Java Library Plugin

This blog is under a CC BY-NC-SA 3.0 Unported License
Link to this article: https://younggod.netlify.app/2020/04/26/tech/gradle/GradleJavaLibraryPlugin/