javagradlejarbuild.gradleexecutable-jar

Creating runnable JAR with Gradle


Until now I created runnable JAR files via the Eclipse "Export..." functionallity but now I switched to IntelliJ IDEA and Gradle for build automation.

Some articles here suggest the "application" plugin, but this does not entirely lead to the result I expected (just a JAR, no start scripts or anything like this).

How can I achieve the same result Eclipse does with the "Export..." dialog?


Solution

  • An executable jar file is just a jar file containing a Main-Class entry in its manifest. So you just need to configure the jar task in order to add this entry in its manifest:

    jar {
        manifest {
            attributes 'Main-Class': 'com.foo.bar.MainClass'
        }
    }
    

    You might also need to add classpath entries in the manifest, but that would be done the same way.

    See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html


    If you already have defined an application context, you can re-use the definition rather than duplicate it:

    application {
      // Define the main class for the application.
      mainClass = 'com.foo.bar.MainClass'
    }
    
    jar {
      manifest {
        attributes 'Main-Class': application.mainClass
      }
    }