Java

embedding project version / git commit hash / build date inside a Gradle based Spring Boot application

“When did we build this application? Which is this application version?” are always our concern.
If you have a properly configured continuous delivery pipeline, you can check them by just checking when the pipeline was triggered.

But, simply showing the version string inside your application will surely convince you.

Here is the simplest way to embed project version / git commit hash inside your application.

As seen in build.gradle, you can embed build date and time, and result of `git rev-parse –short HEAD` into MANIFEST.MF’s Implementation-Version.

def gitHash = { ->
    def gitProcess = 'git rev-parse --short HEAD'.execute()
    gitProcess.waitFor()
    return gitProcess.text.trim()
}

bootJar {
    manifest {
        attributes(
            'Implementation-Version': "${project.name} ${project.version}(${gitHash}) built on ${LocalDateTime.now()}"
        )
   }
}

You can implement a static method to retrieve the version string,

    public static String getImplementationVersion() {
        return IndexController.class.getPackage().getImplementationVersion();
    }

And lastly,
invoke that method inside a Thymeleaf template as follows:

<div th:text="${T(com.example.gitcommithash.IndexController).getImplementationVersion()}"></div>

You can also embed the string inside HTML comments as follows:

<!--
[[${T(com.example.gitcommithash.IndexController).getImplementationVersion()}]]
-->

Version string will be seen in a web page like this:

Source code:https://github.com/yusuke/spring-boot-git-commit-hash