I am trying to get access to build info values such as version
in my Java main application using Spring Boot and Gradle.
I can't find any documentation / examples of how to configure the
build.gradle
application.yml
(if required)Java main class
could someone please help with a small code example for the above files.
In my build.gradle
file I will have the version
entry, so how to get this into Java main class using Spring Boot and Gradle.
build.gradle
version=0.0.1-SNAPSHOT
I've tried adding
build.gradle
apply plugin: 'org.springframework.boot'
springBoot {
buildInfo()
}
but the buildInfo()
isn't recognised as a keyword in Intellij
In my Java main class I have the following:
public class MyExampleApplication implements CommandLineRunner {
@Autowired
private ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(MyExampleApplication.class, args);
}
@Override
public void run(String[] args) throws Exception{
Environment env = (Environment) context.getBean("environment");
displayInfo(env);
}
private static void displayInfo(Environment env) {
log.info("build version is <" + env.getProperty("version")
}
But when I run this - the output from env.getProperty("version")
is showing as null
.
add following to your Gradle script.It inserts the version into the jar manifest correctly, as shown here:
Your code will be able to pick up the version from that jar manifest file:
Refer the link below for more details: https://github.com/akhikhl/wuff/wiki/Manifest-attributes-in-build.gradle
I managed to get it working now - using the help pointer that Vampire gave below and some other sources. The key was adding the actuator class to the project dependency. Note: Intellj doesn't seem to recognise buildInfo() in the springBoot tag - but it does run ok - so don't be put off.
build.gradle
MyExampleApplication
Screenshot of Console output when running the Application in Intellj
pasting the output as well incase the image doesn't display
UPDATE
After reviewing this with my colleague we decided to move the some of the build properties, e.g.
version
(above) out of thebuild.gradle
file and intogradle.properties
file. This gives us a cleaner separation for build details and properties. When you run Gradle build it automatically pulls these values in and they are available in the BuildProperties bean in the Java main class as shown in the example above.gradle.properties
Easy way to get version number in Spring boot
And dont forget generate application-build.properties
Spring Boot auto-configures a
BuildProperties
bean with the information generated bybuildInfo()
.So to get the information use
context.getBean(BuildProperties.class).getVersion();
.