Yes, it is possible. Spring has a bean named BuildProperties
, which has some project information such as the version number.
For this, you need the following:
1)
a) If the project is Maven, add the following to pom.xml
:
<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>
b) If the project is Gradle, add the following to build.gradle
:
springBoot {
buildInfo()
}
When building the project, Spring will generate the \build\resources\main\META-INF
path in the build-info.properties
path and make the bean BuildProperties
available for injection, which, among other methods, has getVersion()
, which returns the version.
For code this is, however, if you run the project through IDE (which is most likely), you may get a bean error not found. To resolve this, if your IDE is Intellij, go to Edit > Settings > Build, Execution, Deployment > Gradle (ou Maven, depende do seu projeto) > Runner
and click the Delegate IDE build / run actions to gradle (or maven) option. This is because the Gradle / Maven task that generates the build-info.properties
file is bootBuildInfo
, which is not the default task Intellij uses, hence the error.
When running System.out.println(build.getVersion());
on a test project following the steps I described, I received as output the version that is informed in the project build.gradle
:
//0.0.1-SNAPSHOT
A useful article can be found here .