Automagically generate version of a Spring Boot Application

TL;DR This post is a hands-on description how to show the current version - plus Git commit hash - during startup together with your Spring Boot application banner.

Basically I followed the answer in Getting the Gradle.build version into Spring Boot and the linked Spring Boot reference documentation. Automatic property expansion using Gradle

Within the Spring Boot application.yaml I added the properties application.title and application.version like follows:

application:
  title: ${name}
  version: ${version}

With a trick similar to Automagically generate versionCode and versionName of an Android build we create a nice version including a short Git commit hash - like this 0.1.0-cc627aa3.

With the help of the library grgit we pimp the version in our gradle.build:

version = '0.1.0' + getVersionNameExtension()

You'll have to add the library to your buildscript section:

buildscript {
  dependencies {
    ...
    classpath 'org.ajoberstar:grgit:1.9.3'
    ...
  }
}

...and provide a static method like this:

static getVersionNameExtension() {
  try {
    def git = org.ajoberstar.grgit.Grgit.open()
    def versionNameSuffix = "-${git.head().getAbbreviatedId(8)}"
    git.close()
    return versionNameSuffix
  } catch (ignored) {
    return ""
  }
}

Next I prepared a Spring Boot banner - with the well received Online Spring Boot Banner Generator

,------.  ,--.                             ,--.             ,-----.             ,--.
|  .--. ' |  |  ,--,--. ,--,--,   ,---.  ,-'  '-.  ,---.    |  |) /_   ,---.  ,-'  '-.
|  '--' | |  | ' ,-.  | |      \ | .-. : '-.  .-' (  .-'    |  .-.  \ | .-. | '-.  .-'
|  | --'  |  | \ '-'  | |  ||  | \   --.   |  |   .-'  `)   |  '--' / ' '-' '   |  |
`--'      `--'  `--`--' `--''--'  `----'   `--'   `----'    `------'   `---'    `--'

Below the generated banner I added:

${application.title} - ${application.version}

To make those variable available to Spring Boot we process the resources before we compile the code:

compileJava.dependsOn(processResources)

processResources {
    filesMatching("**/*.yaml") {
        expand project.properties
    }
}

On production this will render as follows during startup of the application:

,------.  ,--.                             ,--.             ,-----.             ,--.
|  .--. ' |  |  ,--,--. ,--,--,   ,---.  ,-'  '-.  ,---.    |  |) /_   ,---.  ,-'  '-.
|  '--' | |  | ' ,-.  | |      \ | .-. : '-.  .-' (  .-'    |  .-.  \ | .-. | '-.  .-'
|  | --'  |  | \ '-'  | |  ||  | \   --.   |  |   .-'  `)   |  '--' / ' '-' '   |  |
`--'      `--'  `--`--' `--''--'  `----'   `--'   `----'    `------'   `---'    `--'
planets-bot - 0.1.0-cc627aa3

Whenever you analyze some logs you'll always know which code produced the given output.