Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get maven project.version property in a Spring application with @Value

How to get the maven project.version property in a Spring Boot application with a @Value annotation?

like image 515
Jack G. Avatar asked Aug 16 '16 20:08

Jack G.


People also ask

How do I get property properties from spring boot?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

Can we update application properties in spring boot?

You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties. Later you can write back the properties to the same file using the FileOutputStream .

Where is application properties in spring boot?

Spring Boot Framework comes with a built-in mechanism for application configuration using a file called application. properties. It is located inside the src/main/resources folder, as shown in the following figure. Spring Boot provides various properties that can be configured in the application.


1 Answers

After some research and trials on how to get the Maven project version in a SpringBoot application I couldn't find anything working for me.

Using a manifest is definitively a rotten path due to class loaders issues, i.e. one gets the first manifest Spring finds, which in my case was not the one of my application.

One solution I have found is to use the maven resources plugin to "filter" (replace) properties in resource files. In this case the Spring application.properties.

Below are the steps to make this work.

In the pom file, activate resources filtering with the following definition:

<resources>     <resource>         <filtering>true</filtering>         <directory>src/main/resources</directory>         <includes>             <include>application.properties</include>         </includes>     </resource> </resources> 

In the application.properties file:

[email protected]@ [email protected]@ build.timestamp=@timestamp@ 

Notice the @property@ instead of ${property}. in the application.properties file.

The spring-boot-starter-parent pom redefines the standard ${} delimiter as @:

<resource.delimiter>@</resource.delimiter> <!-- delimiter that doesn't clash with Spring ${} placeholders --> <delimiters>     <delimiter>${resource.delimiter}</delimiter> </delimiters> 

One can then access those properties in Spring using @Value like this:

@Value("${application.name}") private String applicationName;  @Value("${build.version}") private String buildVersion;  @Value("${build.timestamp}") private String buildTimestamp; 

A sample project is available here.

like image 198
Jack G. Avatar answered Nov 24 '22 01:11

Jack G.