The application plugin and gradle run

The java plugin builds a jar. The application plugin adds what a program needs around that jar: a task that runs it from the build, a start script for Linux and one for Windows, and a zip that holds both. One line names the class to run.

The plugin and mainClass

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'java' id 'application' } version = '1.0.0' application { mainClass = 'com.example.App' }

src/main/java/com/example/App.java

package com.example; import java.util.Arrays; public final class App { public static void main(String[] args) { System.out.println("shop 1.0.0"); if (args.length > 0) { System.out.println("args: " + Arrays.toString(args)); } } }

gradle run

gradle run --console=plain --offline --no-daemon

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :run
shop 1.0.0

BUILD SUCCESSFUL in 14s
2 actionable tasks: 2 executed

The run task is a JavaExec: it builds the class path of the main source set, starts a JVM with it and runs mainClass. Its output appears between the task lines, because the program writes to the same terminal as the build.

Arguments

--args passes one string to the program, split into arguments the way a shell would:

gradle run --args="--fast two" --console=plain --offline --no-daemon

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE

> Task :run
shop 1.0.0
args: [--fast, two]

BUILD SUCCESSFUL in 12s
2 actionable tasks: 1 executed, 1 up-to-date

The distribution

gradle build --console=plain --offline --no-daemon

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar
> Task :startScripts
> Task :distTar
> Task :distZip
> Task :assemble
> Task :compileTestJava NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
> Task :check UP-TO-DATE
> Task :build

BUILD SUCCESSFUL in 14s
5 actionable tasks: 4 executed, 1 up-to-date

ls build/distributions build/scripts

build/distributions:
shop-1.0.0.tar
shop-1.0.0.zip

build/scripts:
shop
shop.bat

The zip holds a bin/ folder with the two start scripts and a lib/ folder with the jar of the project and every runtime dependency. It is the archive to hand to somebody who has a JVM and no Gradle: unpack it and run bin/shop.

The start scripts name the class path and the main class; the jar itself still has no Main-Class attribute, which is the subject of the next lesson.

Related

Article author: Arthur Isaev