Sometimes we need to know what version of an application is deployed and running. In this post today I will show how we can achieve this.
Contents
Adding the plugin in pom.xml
First, we need to add a plugin in the pom.xml . When you have this then you can refer project.version to your properties file. We also need to make sure that the resource file is included in the war file so that the properties file is part of the build.
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!--plugins for build info-->
<plugin>
<groupId>org.apache.maven.plugins<groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot<groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Adding a field in application.properties file
You can add the below line in application.properties file which will be under src->main->resources. During application is compiled the @project.version@ that will be replaced by actual project.version from pom after the final jar/war is generated. The build.version will have a particular version when the app war is created and it is deployed.
build.version=@project.version@
Writing a spring configuration class to access the build version from properties file
Now you can write a class to access the field from application.properties file Let’s say we want to access this variable in properties file from an class AppInfo.java. The code will look like this.
package com.mycomp.myproject.xxx.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.PostConstruct;
@Configuration
@PropertySources({
@PropertySource(classpath:application.properties)
})
public class AppInfo {
@Value("${build.version}")
private String appVresion;
this will automatically initialize appVersion with the value from build.version
}
@PostConstruct
public void init() { print();}
public void print() {
logger.info(" appVresion : " + appVresion);
}
I have created a spring configuration class that will be initialized during the application deployment. The appVersion variable will be automatically initialized with the value from the build.version field of the application.properties
This will help access the application build version through this class whenever and whatever places of the application we would like to. FOr example I have printed the value using the print() method after the bean is constructed (refer to the @PostConstruct annotation).
The PropertySources and PropertySource specifies in which file the Value should be searched, it is helpful when you have multiple resource files.
Commenti