Introduction

The badass-jlink plugin allows you to create custom runtime images with minimal effort.

Many modular applications have one or more non-modular dependencies, which are treated as automatic modules by the Java platform. However, jlink cannot work with automatic modules. The typical way to solve this problem is to convert the non-modular jars to explicit modules, by adding an appropriate module descriptor to each non-modular jar. This is a tedious process if your application has lots of non-modular dependencies.

The badass-jlink plugin takes a more pragmatic approach by combining all non-modular dependencies into a single jar. This way, only the resulting merged module needs a module descriptor.

The plugin provides several tasks. The most frequently used are jlink, which creates a custom runtime image in a given directory, and jlinkZip, which in addition creates a zip archive of the custom runtime image.

The plugin requires Java 11 and Gradle 4.8 or newer. While it might work with some combinations of older Java and Gradle versions, these are not officially supported.

If you use Gradle 5 or newer, include the following in your build script:

plugins {
    id 'org.beryx.jlink' version '2.1.3'
}

We also provide a version compatible with Gradle 4:

plugins {
    id 'org.beryx.jlink' version '2.1.3-gradle4'
}

Applying the Badass-JLink plugin also implicitly applies the Application plugin.

The plugin uses an extension named jlink. The sample below shows a few configuration options.

jlink {
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher{
        name = 'hello'
        jvmArgs = ['-Dlog4j.configurationFile=./log4j2.xml']
    }
}

The next sections provide detailed information on how to configure the plugin.

The source code is available on GitHub and is licensed under the Apache-2.0 license.

User Guide

Creating a custom runtime image can be a challenging task if your application has many non-modular dependencies. To let you address all possible issues, badass-jlink allows you to configure the jlink extension using various properties, methods and script blocks.

The operations required to create a custom runtime image are grouped in several tasks. This gives you the possibility to tweak a particular step by hooking into the corresponding task (via doFirst, doLast, TaskExecutionListener or TaskActionListener).

Tasks

prepareMergedJarsDir

Unpacks all non-modular dependencies in a designated directory.
depends on: jar

createMergedModule

Creates the merged module using the content of the directory prepared by the previous task and adding a module descriptor to it.
depends on: prepareMergedJarsDir

createDelegatingModules

For each non-modular dependency, it creates a delegating module, which is an open module consisting only of a module descriptor. The module descriptor specifies that the delegating module requires transitive the merged module.
depends on: createMergedModule

prepareModulesDir

Copies all modules needed by jlink to a designated directory.
depends on: createDelegatingModules

jlink

Uses the jlink tool to create the custom runtime image.
depends on: prepareModulesDir

jlinkZip

Creates a zip archive of the custom runtime image.
depends on: jlink

suggestMergedModuleInfo

Displays the mergedModule block that will be used if your jlink extension doesn’t include one. You can use the suggested block as a starting point for your custom mergedModule block.
depends on: prepareMergedJarsDir

A detailed description of these tasks is given in Task details

Properties

imageDir

The directory into which the custom runtime image should be generated.
(If you use the targetPlatform method to generate images for other platforms, the corresponding images will be created in subdirectories of imageDir.)
defaultValue: buildDir/image
usage example: imageDir = file("$buildDir/myapp-image")

imageZip

The file into which a zip archive of the custom runtime image should be created.
defaultValue: buildDir/image.zip"
usage example: imageZip = file("$buildDir/myapp-image.zip")

jlinkBasePath

The path to the base directory that will be used by the plugin to store intermediate outputs.
defaultValue: buildDir/jlinkbase
usage example: jlinkBasePath = "$buildDir/my-jlinkbase"

mainClass

The main class to be provided as part of the --launcher option of jlink.
defaultValue: project.mainClassName (from the Application plugin)
usage example: mainClass = 'org.example.MyApp'

moduleName

The module name of this application.
defaultValue: the module name specified in this application’s module-info.java
usage example: moduleName = 'org.example.myapp'

mergedModuleName

The name of the merged module.
defaultValue: moduleName.merged.module
usage example: mergedModuleName = 'org.example.myapp.merged.module'

options

A list of options to be passed to jlink.
defaultValue: empty list
usage example: options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']

javaHome

The path to the JDK providing the tools needed by the plugin (javac, jar, jlink etc.).
defaultValue: the value of the JAVA_HOME environment variable.
usage example: javaHome = '/usr/lib/jvm/open-jdk'

Methods

addOptions(String…​ options)

Adds options to be passed to jlink. It is an alternative way of setting the options property. You can call this method multiple times.
usage example: addOptions '--no-header-files', '--no-man-pages'

forceMerge(String…​ jarPrefixes)

Instructs the plugin to include all dependencies matching the given prefixes into the merged module. This method is useful when the plugin should handle one or more modular jars as non-modular. You can call this method multiple times.
usage example: forceMerge 'jaxb-api'

addExtraDependencies(String…​ jarPrefixes)

Instructs the plugin to treat all jars matching the given prefixes as dependencies of the merged module.
A typical situation where this method is needed involves libraries using JavaFX. Some libraries do not specify their JavaFX dependencies, because JavaFX was part of the JDK before being removed in Java 11.
Including addExtraDependencies("javafx") into the jlink block solves this problem.

targetPlatform(String name, String jdkHome, List<String> options = [])

Instructs the plugin to generate an application image for a specific platform.
By default, the plugin generates an image for the platform it runs on. To create images for other platforms, you need to call the targetPlatform method (one call per target platform).
name: an identifier of your choice that will be appended to the imageDir and imageZip properties to determine the location of the image directory and of the image archive.
jdkHome: the path to the target platform JDK.
options: an optional list of platform-specific options. These options will pe passed to jlink in addition to those provided by the options property of the jlink extension.

Usage example
jlink {
    ...
    targetPlatform('linux-x64', '/usr/lib/jvm/jdk_x64_linux_hotspot_11_28')
    targetPlatform('linux-s390x', '/usr/lib/jvm/jdk_s390x_linux_hotspot_11_28',
                                                               ['--endian', 'big'])
    ...
}

For a project named hello, executing the jlinkZip task with the above configuration, and assuming default values for the other properties, the plugin will generate the platform-specific images in the directories build/image/hello-linux-x64 and build/image/hello-linux-s390x. The archived images will be available in build/image-linux-x64.zip and build/image-linux-s390x.zip.

Script blocks

The jlink extension can also contain the script blocks detailed below.

mergedModule

The mergedModule block allows you to configure the module descriptor of the merged module. It provides a DSL that matches the syntax of the directives in a module declaration file (module-info.java), but it requires quotes around the names of modules, services, and service implementation classes.

The plugin automatically exports all packages found in the merged module, therefore the DSL does not support exports directives.

Usage example (Groovy DSL)
jlink {
    ...
    mergedModule {
        requires 'java.desktop'
        requires transitive 'java.sql'
        uses 'java.sql.Driver'
        provides 'java.sql.Driver' with 'org.hsqldb.jdbc.JDBCDriver'
    }
    ...
}
Usage example (Kotlin DSL)
import org.beryx.jlink.data.ModuleInfo
...
jlink {
    ...
    mergedModule (delegateClosureOf<ModuleInfo> {
        requires("java.desktop")
        requiresTransitive("java.sql")
        uses("java.sql.Driver")
        provides("java.sql.Driver").with("org.hsqldb.jdbc.JDBCDriver")
    })
    ...
}

launcher

The plugin generates script files for launching your application. You can customize these scripts by configuring the following properties in the launcher block.

name

The base name of the script files used to launch your aplication.
defaultValue: project.name

jvmArgs

list of JVM arguments to be passed to the java executable.
defaultValue: empty list

args

list of arguments to be passed to the application.
defaultValue: empty list

unixScriptTemplate

the template for generating the script file for Unix-like systems.
defaultValue: null (the plugin uses its own template)

windowsScriptTemplate

the template for generating the script file for Windows-based systems.
defaultValue: null (the plugin uses its own template)

The plugin uses Groovy’s SimpleTemplateEngine to parse the templates, with the following variables available:

  • moduleName

  • mainClassName

  • jvmArgs

  • args

Usage example (Groovy DSL)
jlink {
    ...
    launcher {
        name = 'my-app'
        jvmArgs = ['-Dlog4j.debug=true', '-Dlog4j.configurationFile=./log4j2.xml']
        args = ['--user', 'alice']
        unixScriptTemplate = file('unixStartScript.txt')
        windowsScriptTemplate = file('windowsStartScript.txt')
    }
    ...
}
Usage example (Kotlin DSL)
import org.beryx.jlink.data.LauncherData
...
jlink {
    ...
    launcher (delegateClosureOf<LauncherData> {
        name = "my-app"
        jvmArgs = listOf("-Dlog4j.debug=true", "-Dlog4j.configurationFile=./log4j2.xml")
        args = listOf("--user", "alice")
        unixScriptTemplate = file("unixStartScript.txt")
        windowsScriptTemplate = file("windowsStartScript.txt")
    })
    ...
}

How it works

The plugin combines all non-modular dependencies into a single jar to which it adds a module descriptor. If the jlink extension contains a mergedModule block, its directives will be used to generate the module descriptor. Otherwise, a module descriptor is created using the algorithm implemented by the suggestMergedModuleInfo task.

The non-modular dependencies appear as automatic modules in the original module graph. The plugin replaces them with delegating modules, which are dummy modules containing only a module descriptor that requires transitive the merged module.

The figure below illustrates this process.

merging

In some situations, the above approach would lead to cyclic dependencies between modules. For example, in the module graph below the automatic module org.example.mod1 requires the proper module org.example.mod2. Because the content of org.example.mod1 gets merged into the merged module, the merged module must require org.example.mod2. This in turn requires the delegating module org.example.mod3 and hence the merged module.

merging.cycle

To prevent such problems, the plugin automatically detects the modular jars that would be involved in a cycle and treats them as if they were non-modular. This means that it also merges these modular jars into the merged module and replaces them with delegating modules. The figure below shows the resulting module graph.

merging.no cycle

Sometimes, you may want to have a modular jar treated as non-modular, even if it is not affected by a cyclic dependency problem. You can do this using the forceMerge method.

Task details

The following properties denote files and directories used by the plugin tasks:

  • imageDir - the directory into which the custom runtime image should be generated.

  • imageZip - the file into which a zip archive of the custom runtime image should be created.

  • jlinkBasePath - the path to the base working directory of the plugin. The table below shows the variable names of the subdirectories created here and their relative path to the base working directory:

Variable namePath relative to jlinkBasePath
mergedJarsDirmergedjars
tmpMergedModuleDirtmpmerged
jlinkJarsDirjlinkjars
tmpjars
tmpModuleInfoDirtmpmodinfo
delegatingModulesDirdelegating

prepareMergedJarsDir

- clean jlinkBasePath
- copy modular jars required by non-modular jars to jlinkJarsDir
- copy non-modular jars to nonModularJarsDir
- unpack all jars from nonModularJarsDir into mergedJarsDir
- create MANIFEST.MF in mergedJarsDir

createMergedModule

- archive mergedJarsDir into tmpMergedModuleDir/mergedModuleName.jar
- generate module-info.java for the above merged jar into tmpJarsDir
- clean tmpModuleInfoDir and unpack the merged jar in it
- compile the generated module-info.java into tmpModuleInfoDir
        using jlinkJarsDir as module-path
- copy the merged jar into jlinkJarsDir
- insert the module-info.class from tmpModuleInfoDir into the merged jar

createDelegatingModules

- delete tmpJarsDir
- for each file in nonModularJarsDir:
    - create delegating module-info.java into tmpJarsDir/<current-module-name>
    - clean tmpModuleInfoDir and create MANIFEST.MF in it
    - compile module-info.java into
            tmpModuleInfoDir with jlinkJarsDir as module-path
    - create a jar of tmpModuleInfoDir into delegatingModulesDir

prepareModulesDir

- copy delegating modules from delegatingModulesDir to jlinkJarsDir
- copy modular jars not required by non-modular jars to jlinkJarsDir
- delete imageDir
- create custom runtime image in imageDir by executing jlink
        with modules from jlinkJarsDir and project.jar.archivePath

jlinkZip

- zip imageDir to imageZip

suggestMergedModuleInfo

- determine the modules required by the merged module
- determine the services used by the merged module
- determine the services provided by the merged module
- print the suggested `mergedModule` block
Options
language

the DSL for which the mergedModule block should be displayed.
default value: groovy
accepted values: groovy, kotlin, java
usage example: ./gradlew suggestMergedModuleInfo --language=kotlin

Examples

The following projects illustrate how to use this plugin to create custom runtime images: