Bundling up the application as a runnable JAR file
We've hacked out a suitable application. Now it's time to take it to production. As Spring Developer Advocate Josh Long likes to say, production is the happiest place on earth.
The good ol' spring-boot-gradle-plugin
has built-in hooks to handle that for us. By invoking Gradle's build
task, it will insert itself into the build process, and create a JAR file.
$ ./gradlew clean build:clean:compileJava:processResources:classes:findMainClass:jar:bootRepackage:assemble:compileTestJava:processTestResources UP-TO-DATE:testClasses:test... test output ...:check:buildBUILD SUCCESSFULTotal time: 10.946 secs
If we peek at the output, we'll find the original JAR file (non-FAT) along with the rebundled one containing our application code as well as the third-party dependencies, as shown here:
$ ls build/libslearning-spring-boot-0.0.1-SNAPSHOT.jarlearning-spring-boot-0.0.1-SNAPSHOT.jar.original
Note
If you wish to check out the newly minted JAR's contents, type jar tvf build/libs/learning-spring-boot-0.0.1-SNAPSHOT.jar
. We won't show it here because of space constraints.
The über JAR is nicely loaded up with our custom code, all of our third-party dependencies, and a little Spring Boot code to allow us to run it. Why not try that out right here?
Let's type the following command:
$ java -jar build/libs/learning-spring-boot-0.0.1-SNAPSHOT.jar
We can expect the same output as before, which is as seen in this image:
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.0.0.M5)2017-09-19 20:41:20.036: Starting LearningSpringBootApplication on ret......... the rest has been cut for space ...
By invoking the JAR using Java's -jar
option, we can launch the application with nothing more than the JVM on our machine.
With our JAR file in hand, we can take our application anywhere. If we need to override any settings, we can do it without cracking it open and making alterations.
Suppose we alter our command slightly, like this:
$ SERVER_PORT=8000 java
-jar build/libs/learning-spring-boot-0.0.1-SNAPSHOT.jar
We can now expect the results to be a little different, as seen in this image:
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.0.0.M5)...2017-08-03 15:40:02.489: Netty started on port(s): 8000...
From the command line, we override server.port
using an alternative notation (SERVER_PORT
) and run it on port 8000
.
This lends us the ability to deploy it into the cloud.