display application version in title using thymeleaf and springboot
I know I'm late but Patrick's answer and Spring docs greatly helps in this matter.
1. If your pom.xml use spring-boot-starter-parent as parent, you can use @project.version@
to get version (and any other Maven properties) in your application.properties file. According to Spring docs:
You can automatically expand properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via @..@ placeholders
Maven pom.xml:
<groupId>com.foo</groupId>
<artifactId>bar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Foo</name>
<description>Bar</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Spring application.properties:
[email protected]@
2. Then a class annotated with @ControllerAdvice
can be used to inject version as model attribute.
@ControllerAdvice
public class ControllerAdvice {
@Value("${foo.app.version}")
private String applicationVersion;
@ModelAttribute("applicationVersion")
public String getApplicationVersion() {
return applicationVersion;
}
}
3. Finally this model attribute can be accessed by Thymeleaf as any other.
<th:block th:text="${applicationVersion}"></th:block>
Hope this helps!
Here is the simplest way I've found : In my controller :
@ModelAttribute("version")
public String getVersion() throws IOException {
logger.info("ModelAttribute to get application version");
Manifest manif = new Manifest(
Application.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
String version = (String) manif.getMainAttributes().get(
Attributes.Name.IMPLEMENTATION_VERSION);
return version;
}
In my htm page :
<h4 th:text="${version}">Version</h4>