These tutorials target Micronaut Framework 3. Read, Guides for Micronaut Framework 4.

Adding Commit Info to your Micronaut Application

Expose the exact version of code that your application is running.

Authors: Sergio del Amo

Micronaut Version: 3.9.2

In this guide, we will add git commit info to your Micronaut build artifacts and running application. There are many benefits of keeping your commit info handy:

  • Commit info is encapsulated within the built artifacts

  • Fast authoritative means of identifying what specific code is running in an environment

  • This solution doesn’t rely on external tracking mechanisms

  • Transparency and reproducibility when investigating issues

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 11 or greater installed with JAVA_HOME configured appropriately

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Before running the downloaded project, follow the steps described in the Initialize Git Repository section below.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide --build=gradle --lang=java
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

5. Initialize Git Repository

The project aims to demonstrate how to provide Git commit information to the /info endpoint and in order for that to work the project needs to be in a Git repository. After creating the project, initialize a Git repository from the root of the newly created project:

cd micronautguide
git init
git add .
git commit -a "Initial project"

6. Management

Inspired by Spring Boot and Grails, the Micronaut management dependency adds support for monitoring of your application via endpoints: special URIs that return details about the health and state of your application.

To use the management features described in this section, add the dependency on your classpath.

build.gradle
implementation("io.micronaut:micronaut-management")

7. Info endpoint

The info endpoint returns static information from the state of the application. The info exposed can be provided by any number of "info sources".

Enable the info endpoint:

src/main/resources/application.yml
endpoints:
  info:
    enabled: true
    sensitive: false

8. Gradle Git Properties Plugin

If a git.properties file is available on the classpath, the GitInfoSource will expose the values in that file under the git key. Generation of a git.properties file will need to be configured as part of your build.

For example, you may choose to use the Gradle Git Properties plugin. The plugin provides a task named generateGitProperties responsible for the git.properties file generation. It is automatically invoked upon the execution of the classes task. You can find the generated file in the directory build/resources/main.

Modify build.gradle file to add the plugin:

build.gradle
plugins {
  id "com.gorylenko.gradle-git-properties" version "@gradle-git-propertiesVersion@"
}

9. Test

Create a JUnit test to verify that when you make a GET request to /info you get a payload such as:

{
  "git": {
    "dirty": "true",
    "commit": {
      "id": "7368906193527fbf2b45f1ed5b08c56631f5b155",
      "describe": "7368906-dirty",
      "time": "1527429126",
      "message": {
        "short": "Initial version",
        "full": "Initial version"
      },
      "user": {
        "name": "sdelamo",
        "email": "sergio.delamo@softamo.com"
      }
    },
    "branch": "master"
  }
}

Create a JUnit test to verify the behaviour:

src/test/java/example/micronaut/InfoTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import jakarta.inject.Inject;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@MicronautTest (1)
public class InfoTest {

    @Inject
    @Client("/")
    HttpClient client; (2)

    @Test
    public void testGitComitInfoAppearsInJson() {
        HttpRequest request = HttpRequest.GET("/info"); (3)

        HttpResponse<Map> rsp = client.toBlocking().exchange(request, Map.class);

        assertEquals(200, rsp.status().getCode());

        Map json = rsp.body(); (4)

        assertNotNull(json.get("git"));
        assertNotNull(((Map) json.get("git")).get("commit"));
        assertNotNull(((Map) ((Map) json.get("git")).get("commit")).get("message"));
        assertNotNull(((Map) ((Map) json.get("git")).get("commit")).get("time"));
        assertNotNull(((Map) ((Map) json.get("git")).get("commit")).get("id"));
        assertNotNull(((Map) ((Map) json.get("git")).get("commit")).get("user"));
        assertNotNull(((Map) json.get("git")).get("branch"));
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.
3 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
4 Use .body() to retrieve the parsed payload.

10. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

11. Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

12. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

12.1. Native executable generation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 11
sdk install java 22.3.r11-grl
If you still use Java 8, use the JDK11 version of GraalVM.
Java 17
sdk install java 22.3.r17-grl

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

After installing GraalVM, install the native-image component, which is not installed by default:

gu install native-image

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle
graalvmNative {
    binaries {
        main {
            imageName.set('mn-graalvm-application') (1)
            buildArgs.add('--verbose') (2)
        }
    }
}
1 The native executable name will now be mn-graalvm-application
2 It is possible to pass extra arguments to build the native executable

Annotate the Application class with @Introspected. This won’t be necessary in a real world application because there will be Micronaut beans defined (something annotated with @Singleton, @Controller,…​), but for this case we need to annotate a class so the visitor that generates the GraalVM resource-config.json file is triggered:

src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.core.annotation.Introspected;
import io.micronaut.runtime.Micronaut;

@Introspected
public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

The git.properties file that is generated by the gradle-git-properties plugin will not be accessible from the native executable unless access to the file is configured in resource-config.json:

src/main/resources/META-INF/native-image/resource-config.json
{
  "resources": [
    {"pattern":"\\Qgit.properties\\E"}
  ]
}

You can execute the info endpoint exposed by the native executable:

curl localhost:8080/info
{"git":{"dirty":"true","total":{"commit":{"count":"45"}},"build":{"host":"Sergios-iMac-Pro.local","time":"2019-12-09T09:35:30+0100","user":{"name":"Sergio del Amo","email":"sergio.delamo@softamo.com"},"version":"0.1"},"commit":{"time":"2019-12-09T09:30:41+0100","id":"af3cff433d247fd4c2d8c54ae200108e98adfb2a","message":{"short":"add help section","full":"add help section\n"},"user":{"name":"Sergio del Amo","email":"sergio.delamo@softamo.com"}},"remote":{"origin":{"url":"git@github.com:micronaut-guides/adding-commit-info.git"}},"branch":"master"}}

13. Next steps

Explore more features with Micronaut Guides.

14. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.