How to run shadow jar with a gradle task?

Appyx picture Appyx · Mar 16, 2019 · Viewed 15.1k times · Source

I want to run my app after building it with the shadow jar plugin.

build.gradle:

plugins {
    id 'java'
    id "org.jetbrains.kotlin.jvm" version "1.3.21"
    id "com.github.johnrengelman.shadow" version "5.0.0"
}

group 'org.example.java'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

repositories {
    jcenter()
}

dependencies {
    compile "io.ktor:ktor-server-netty:1.1.3"
}

I also have a global init.gradle:

gradle.projectsLoaded {
    rootProject.allprojects {
        buildDir = "/Users/User/Builds/${rootProject.name}/${project.name}"
    }
}

So now the fat jar can be built to my global build directory with the shadowJar task. But I want to be able to run and build it with just one run configuration in IntelliJ. How do I do that?

Maybe there is another way to let gradle redirect all my output to a global build directory. I don't want to configure each IntelliJ project with the same output path manually. Suggestions are welcome.

Thank you :)

Answer

Louis Jacomet picture Louis Jacomet · Mar 18, 2019

You should not touch the buildDir property for achieving what you want.

Instead, you should create a JavaExec task that will start the application from the shadow jar. If you want that execution to be at a different place than the default location of the generated jar, you should either change the output of the shadow task itself, and only that output or make your execution task depend on a copy task that would move the shadow jar around.

Something like:

shadowJar {
    destinationDir = "/Users/User/Builds/${rootProject.name}/${project.name}"
}

task runApp(type: JavaExec) {
    main = "your.main.Class
    classpath = shadowJar.archiveFile // use archivePath before Gradle 5.1
}