others-how to add JVM args/options/parameters when using gradle?

1. Purpose

In this post, I will demonstrate how to add JVM args/options/parameters when using gradle.

Sometimes, when you are using build.gradle to build your java applications, you might want to start it in command line using gradle command with some customized parameters.

2. Solution

First add the application plugin in build.gradle as follows:

plugins {
    id("application")
}

The Application plugin facilitates creating an executable JVM application. It makes it easy to start the application locally during development, and to package the application as a TAR and/or ZIP including operating system specific start scripts.

Applying the Application plugin also implicitly applies the Java plugin. The main source set is effectively the “application”.

Applying the Application plugin also implicitly applies the Distribution plugin. A main distribution is created that packages up the application, including code dependencies and generated start scripts.

Then add options to application block as follows in build.gradle:

application {
    mainClass = 'com.bswen.myapp.Main'
}

Here you can see that We have specified the java main class using mainClass param:

    mainClass = 'com.bswen.myapp.Main' //replace it with your main class

And you can also specify the java startup maximum and minimum heap memory size as follows:

application {
    applicationDefaultJvmArgs = ["-Xmx512m", "-Xms256m"]
}

And if you have only one JVM argument, you can just do as follows:

application {
    applicationDefaultJvmArgs = ['-Dgreeting.language=en']
}

You can see that we can use applicationDefaultJvmArgs to set the JVM arguments which the application use to start.

Now you can start JVM with customized parameters as follows:

./gradlew run --args='"arg1 arg2"'

The arg1 and arg2 are passed to your main class

Now after packaging the java application, you can start it as follows:

java -jar yourapp.jar "arg1" "arg2"

3. Summary

In this post, I demonstrated how to set JVM arguments in gradle when using gradle . That’s it, thanks for your reading.

To get more information ,you can refer to this document.