how to export a executable jar in gradle, and this jar can run as it include reference libraries

前端 未结 5 2289
长情又很酷
长情又很酷 2020-12-25 10:15

how to export a executable jar in gradle, and this jar can run as it include reference libraries.

build.gradle

apply plugin: \'java\'

manifest.mainA         


        
5条回答
  •  梦谈多话
    2020-12-25 11:08

    All of these answers are either wrong or out of date.

    The OP is asking for what is known as a "fat jar". That is an exectuable jar which contains all the dependencies so that it requires no outside dependencies in order to run (except for a JRE of course!).

    The answer at the time of writing is the Gradle Shadow Jar plugin, explained pretty clearly at Shadow Plugin User Guide & Examples.

    I struggled a bit. But this works:

    put all these lines somewhere in your build.gradle file (I put them near the top) :

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4' 
        }
    }
    apply plugin: 'com.github.johnrengelman.shadow'
    shadowJar {
        baseName = 'shadow'
        classifier = null
        version = null
    }
    jar {
        manifest {
            attributes 'Class-Path': '/libs/a.jar'
            attributes 'Main-Class': 'core.MyClassContainingMainMethod'
        }
    }
    

    PS don't worry about any other "repositories", "dependency" or "plugin" lines elsewhere in your build file, and do leave the lines thus inside this "buildscript" block (I haven't a clue why you need to do that).

    PPS the Shadow Plugin User Guide & Examples is well-written but doesn't tell you to include the line

    attributes 'Main-Class': 'core.MyClassContainingMainMethod'
    

    where I've put it above. Perhaps because the author assumes you are less clueless than I am, and you probably are. I haven't a clue why we are told to put a strange "Class-Path" attribute like that in, but if it ain't broke don't fix it.

    When you then go

    > gradle shadowjar
    

    Gradle will hopefully build a fat executable jar under /build/libs (default name "shadow.jar") which you can run by doing this:

    > java -jar shadow.jar
    

提交回复
热议问题