Customizing the Gradle run task

The Gradle application plugin provides you with a run task to run your Java application (provided you have set the mainClassName). But how do you customize it, e.g. by setting extra JVM arguments? No amount of searching helped me so I want to share what I have learned.

The run task is of the type JavaExec and accepts the same settings, such as args, debug, debugOptions, jvmArgs, environment, systemProperties. And you can configure it simply by declaring it:

build.gradle
apply plugin: 'application'
mainClassName = "my.app.Main"

run {

  debugOptions {
      enabled = true
      server = true
      suspend = false
  }

  systemProperty("my.defaultLogLevel", "debug")
  environment("OTEL_EXPORTER", "zipkin")
  jvmArgs=["-javaagent:aws-opentelemetry-agent-0.9.0.jar"]
  args += "my-extra-arg"
}

Now I can run it with e.g. ./gradlew run and all the options will take effect.

As the application plugin documentation states, you can also enable debugging with --debug-jvm or specify arguments with --args="foo --bar". And you can set application { applicationDefaultJvmArgs= []} to apply both to run and the generated start scripts of your distribution.

(This has been written for Gradle 5 but I imagine it will stay valid for quite a while.)



Copyright © 2024 Jakub Holý
Powered by Cryogen
Theme by KingMob