Gradle application plugin with multiple main classes

前端 未结 4 1375
南方客
南方客 2021-02-20 04:55

I\'m using the gradle \'application\' plugin to start my application. This works well. Now I want to add the option to start a different main class in the same project. Can I ch

相关标签:
4条回答
  • 2021-02-20 05:01

    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)
    }
    
    0 讨论(0)
  • 2021-02-20 05:04

    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.

    0 讨论(0)
  • 2021-02-20 05:10

    Use javaExec task to handle it :

    task run(type: JavaExec) {
        classpath = sourceSets.main.runtimeClasspath
    
        if (project.hasProperty('first')){
            if (chooseMain == 'Main1'){
                main = 'application.Main1'
            } else if (chooseMain == 'second'){
                main = 'application.Main2'
            }
        } else {
            println 'please pass the main name'
        }
    }
    

    And from the command line pass your option in that way :

    gradle run -PchooseMain=first
    
    0 讨论(0)
  • 2021-02-20 05:24

    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
    
    0 讨论(0)
提交回复
热议问题