Detecting build version and time at runtime in Spring Boot
Categories: Spring Boot
Obtaining build information
It can often be useful to obtain information about artifact, version, build time and other at runtime. Sure, most of this information is already in your pom.xml file, but it can be tricky to retrieve these when the application is running.
Having such information at runtime can be useful. For example, imagine a scenario, where you expose a REST endpoint, which can tell the client what your current version of the application is, when was it built and so on. It can be useful because you can quickly determine what version of the app is currently deployed. This can be especially important in non-production environments, where the app is frequently deployed or even with continuous deployment in production. In such cases, it is vital to know what build exactly is currently running when testing and submitting bug reports. Maybe the issue reported is already fixed in a newer version or maybe the bug still occurs because the new version is implemented, but not deployed yet.
In any case, having build information can be handy and it is useful to know how to obtain it at runtime. In Spring Boot, it is fortunately quite easy.
Build plugin configuration
If you are using Spring Boot, your pom.xml should already contain spring-boot-maven-plugin. You just need to add the following configuration.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
It instructs the plugin to execute also build-info goal, which is not run by default. This generates build meta-data about your application, which includes artifact version, build time and more.
If you are using Gradle, just add the following to your build.gradle file:
springBoot {
buildInfo()
}
Accessing Build Properties
After configuring your spring-boot-maven-plugin and building your application, you can access information about your application's build through BuildProperties object. Let the Spring inject it for you:
@Autowired
BuildProperties buildProperties;
Now you can access various information from this object.
// Artifact's name from the pom.xml file
buildProperties.getName();
// Artifact version
buildProperties.getVersion();
// Date and Time of the build
buildProperties.getTime();
// Artifact ID from the pom file
buildProperties.getArtifact();
// Group ID from the pom file
buildProperties.getGroup();
Adding custom properties
If predefined properties are not enough, you can pass your own properties from pom.xml file to BuildProperties.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>