A JAR file!

We want to package our server application as a single executable file that can be run on Heroku. We are going to make a single JAR file1 for this purpose. This JAR contains your application and all the dependencies needed to run your application.

Gradle is able to package your Java application into a JAR file but, by default, it does so without including the project dependencies. We can overwrite the default behavior by adding a few lines to the project's build.gradle:2

jar {
    manifest {
        attributes 'Main-Class' : 'ApiServer'
    }
    from {
        configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

Open the Gradle tool window and refresh the Gradle project. In the Gradle tool window, double click on jar task (as shown below).

Alternatively, you can open the terminal in IntelliJ and run the following command:

./gradlew build jar

Once the process is finished, you can find your newly packaged JAR file in the build/libs directory. Verify that the archive is valid by running it from the terminal: (Before doing this, make sure to stop the server from within IntelliJ if it was running.)

java -jar build/libs/course-search-api-0.0.1.jar

(Notice since I've called my Gradle Java project course-search-api and declared its version as 0.0.1, the produced JAR file is named course-search-api-0.0.1.jar.)

Executing the JAR file must start your API server locally (on localhost) just like when you were running it from within IntelliJ. To verify, go to Postman and send a Get request to http://localhost:4567/api/courses. You must receive the list of sample courses. To stop the server, press control and c keys in the terminal.


1

JAR stands for Java ARchive. It is used for aggregating many Java files into one. It is the preferred way to bundle a Java application. Read more on Oracle's website.

2

You can place the jar configuration anywhere in the build.gradle file; I added it to the end of the file. When you do this for other projects, appropriately change ApiServer to whatever is the "main" class (entry point) of your application.