Yes, it is possible. Spring has a bean called BuildProperties
, that has some project information, such as version number.
For that, you need the following:
1)
a) If the project is Maven, add the following to the 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 the build.gradle
:
springBoot {
buildInfo()
}
When building the project, Spring will generate on the way \build\resources\main\META-INF
the file build-info.properties
and make available for injection the bean BuildProperties
, which, among other methods, has the method getVersion()
, that returns the version.
That’s what code is about, however, if you run the project through the 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 option Delegate IDE build/run actions to Gradle (or Maven). That’s because the Gradle/Maven task that generates the file build-info.properties
is the bootBuildInfo
, which is not the standard task that Intellij uses, hence the error.
When executing System.out.println(build.getVersion());
in a test project following the steps I described, I received as output the version that is informed in build.gradle
of the project:
//0.0.1-SNAPSHOT
A useful article can be found here.
I did as you said but returned the following error: Build script error, Unsupported Gradle DSL method found: 'springBoot()'!
– Celso Ribeiro
got now by changing buildInfo from place in my file Gradle. thanks a lot for the help!
– Celso Ribeiro