Gradle application plugin with multiple main classes

Here's how you can generate multiple start scripts if you need to package your apps

application {
    applicationName = "myapp"
    mainClassName = "my.Main1"
}
tasks.named<CreateStartScripts>("startScripts") {
    applicationName = "myapp-main1"
}
val main2StartScripts by tasks.register("main2StartScripts", CreateStartScripts::class) {
    applicationName = "myapp-main2"
    outputDir = file("build/scripts") // By putting these scripts here, they will be picked up automatically by the installDist task
    mainClassName = "my.Main2"
    classpath = project.tasks.getAt(JavaPlugin.JAR_TASK_NAME).outputs.files.plus(project.configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)) // I took this from ApplicationPlugin.java:129
}
tasks.named("installDist") {
    dependsOn(main2StartScripts)
}

You can directly configure the Application Plugin with properties:

application {
    mainClassName = project.findProperty("chooseMain").toString()
}

And after in command line you can pass the name of the main class:

./gradlew run -PchooseMain=net.worcade.my.MainClass

From http://mrhaki.blogspot.com/2010/09/gradle-goodness-run-java-application.html

apply plugin: 'java'

task(runSimple, dependsOn: 'classes', type: JavaExec) {
   main = 'com.mrhaki.java.Simple'
   classpath = sourceSets.main.runtimeClasspath
   args 'mrhaki'
   systemProperty 'simple.message', 'Hello '
}

Clearly then what you can change:

  • runSimple can be named whatever you want
  • set main as appropriate
  • clear out args and systemProperty if not needed

To run:

gradle runSimple

You can put as many of these as you like into your build.gradle file.

Tags:

Java

Gradle