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

前端 未结 5 2297
长情又很酷
长情又很酷 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:05

    Quick answer

    1. Add the following to your build.gradle:

      apply plugin: 'application'
      
      mainClassName = 'org.example.app.MainClass'
      
      jar {
          manifest {
              attributes 'Main-Class': mainClassName,
                         'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' ')
          }
      }
      
    2. From the project directory, run gradle installDist
    3. Run java -jar build/install//lib/.jar

    I recommend adding the app version to your build.gradle as well, but it's not required. If you do, the built jar name will be -.jar.

    Note: I'm using gradle 2.5


    Details

    In order to create a self contained executable jar that you can simply run with:

    java -jar appname.jar
    

    you will need:

    1. your jar to include a MANIFEST file pointing to your application main class
    2. all your dependencies (classes from jars outside of your application) to be included or accessible somehow
    3. your MANIFEST file to include the correct classpath

    As some other answers point out, you can use some third-party plugin to achieve this, such as shadow or one-jar.

    I tried shadow, but didn't like the fact that all my dependencies and their resources were dumped flat out into the built jar together with my application code. I also prefer to minimize the use of external plugins.

    Another option would be to use the gradle application plugin as @erdi answered above. Running gradle build will build a jar for you and nicely bundle it with all your dependencies in a zip/tar file. You can also just run gradle installDist to skip zipping.

    However, as @jeremyjjbrown wrote in a comment there, the plugin does not create an executable jar per se. It creates a jar and a script which constructs the classpath and executes a command to run the main class of your app. You will not be able to run java -jar appname.jar.

    To get the best of both worlds, follow the steps above which create your jar together with all your dependencies as separate jars and add the correct values to your MANIEST.

提交回复
热议问题