Spring › Feature

Showing the latest Git commit in Spring Boot Swagger UI

Use gradle-git-properties and Spring Boot's GitProperties bean to surface the latest commit hash, branch, and timestamp in Swagger UI safely.

Showing the latest Git commit in Spring Boot Swagger UI

When collaborating with frontend engineers on a shared dev server, questions like “Did my latest PR deploy yet?” come up constantly. This post shows how to surface the deployed commit hash, branch, timestamp, and GitHub diff link directly in Swagger UI using gradle-git-properties and Spring Boot’s GitProperties bean.

Environment: Spring Boot 3.x, Kotlin, Java 21, Gradle Kotlin DSL, springdoc-openapi-starter-webmvc-ui

Why put commit metadata in Swagger UI

After pushing an API change to a development or staging server, frontend and QA teammates often need to verify whether a specific commit is live and which branch is currently running. Checking GitHub Actions logs or container image tags works, but it forces everyone to leave the API documentation they already have open.

Putting deployment metadata right in Swagger UI’s top Info section removes that back-and-forth. Here is how the common options compare:

ApproachProsCons
CI logs or container tagsZero application code requiredSlow for frontend and QA teammates to check
/actuator/infoFits monitoring and automated checksSeparate endpoint from the API docs
Swagger UI Info blockCommit link and timestamp visible on the API pageRequires production gating and a test fixture

This approach works best for internal development and staging environments where teammates already live in Swagger UI. You should not expose commit messages, author emails, or repository URLs on public production endpoints—we’ll lock that down in the production profile below.

Configuring gradle-git-properties and how it works

To pass build-time Git metadata into your Spring Boot application, add the com.gorylenko.gradle-git-properties plugin in build.gradle.kts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// build.gradle.kts
plugins {
    kotlin("jvm") version "1.9.25"
    kotlin("plugin.spring") version "1.9.25"
    id("org.springframework.boot") version "3.5.16"
    id("io.spring.dependency-management") version "1.1.7"
    id("com.gorylenko.gradle-git-properties") version "2.5.7"
}

group = "org.project"
version = "2.0.0"

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.17")
}

With just that plugin applied, Spring Boot wires up a GitProperties bean automatically through three steps:

  1. Build-time resource generation: The plugin hooks its generateGitProperties task into processResources. It reads .git metadata and writes build/resources/main/git.properties.
  2. Conditional auto-configuration: Spring Boot’s ProjectInfoAutoConfiguration checks @ConditionalOnResource(resources = "${spring.info.git.location:classpath:git.properties}"). When the file is on the classpath, it registers a GitProperties bean.
  3. Automatic prefix stripping: GitProperties strips the leading git. prefix from keys, so you can read values with calls like gitProperties.get("commit.message.full") or typed helpers such as gitProperties.branch and gitProperties.shortCommitId.

Wiring GitProperties into SwaggerConfig

Inject the auto-configured GitProperties bean into SwaggerConfig and render the commit details inside the OpenAPI Info object’s description and version fields:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// src/main/kotlin/org/project/portfolio/config/SwaggerConfig.kt
package org.project.portfolio.config

import io.swagger.v3.oas.models.Components
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Contact
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.security.SecurityScheme
import org.springframework.boot.info.GitProperties
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

/** Swagger / OpenAPI configuration */
@Component
class SwaggerConfig(
    private val gitProperties: GitProperties,
) {
    @Bean
    fun openAPI(): OpenAPI {
        return OpenAPI().components(
            Components().apply {
                securitySchemes(
                    mapOf(
                        BEARER_AUTH to securityScheme(),
                    ),
                )
            },
        ).info(info())
    }

    /**
     * Bearer Auth Security Scheme
     */
    private fun securityScheme(): SecurityScheme {
        return SecurityScheme()
            .type(SecurityScheme.Type.HTTP)
            .description(
                """<h3>Bearer Auth</h3>
                <p>Pass the issued JWT token in the Authorization header.</p>
                <p>Bearer [your-jwt-token]</p>
                """.trimIndent(),
            )
            .scheme("bearer")
            .bearerFormat("JWT")
    }

    /**
     * OpenAPI Info
     */
    private fun info(): Info {
        // Apply timezone formatting
        val zonedDateTime: ZonedDateTime = ZonedDateTime.ofInstant(gitProperties.commitTime, ZonedDateTime.now().zone)
        val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm a z")

        // Build direct GitHub commit link
        val commitUrl: String = gitProperties.get("remote.origin.url").replace(".git", "/commit/${gitProperties.shortCommitId}")

        return Info().apply {
            title = "Portfolio Article API"
            description = """<h2>Article API</h2>
                <p>Full source code is available on <a target="_blank" href="${gitProperties.get("remote.origin.url")}">GitHub</a>.</p>
                <p>API documentation generated with springdoc-openapi.</p>
                |<h4>Last Commit Information</h4>
                |<p><strong>Message:</strong> ${gitProperties.get("commit.message.full")}</p>
                |<p><strong>Branch:</strong> ${gitProperties.branch}</p>
                |<p><strong>Commit URL:</strong> <a href="$commitUrl" target="_blank">$commitUrl</a></p>
                |<p><strong>Commit ID:</strong> ${gitProperties.commitId}</p>
                |<p><strong>Commit Time:</strong> ${zonedDateTime.format(formatter)}</p>
                |<p><strong>Committed by:</strong> ${gitProperties.get("commit.user.name")} (${gitProperties.get("commit.user.email")})</p>
            """.trimMargin()
            termsOfService = ""
            contact = Contact().apply {
                name = "Namju Kim"
                email = "user@example.com"
            }
            version = gitProperties.get("build.version")
        }
    }

    companion object {
        const val BEARER_AUTH: String = "Bearer_Authentication"
    }
}

Because gitProperties.commitTime returns an Instant, convert it with ZonedDateTime.ofInstant(...) before formatting. Most Docker base images default to UTC, so either set the container’s TZ environment variable (for example, TZ=Asia/Seoul or TZ=America/New_York) or pass an explicit ZoneId if your team expects local timestamps. Replacing .git in remote.origin.url with /commit/${gitProperties.shortCommitId} turns the commit hash into a one-click GitHub diff link.

Caveats in tests, CI/CD, and production

1. Preventing NoSuchBeanDefinitionException in tests

If your IDE runs tests without triggering Gradle’s processResources task first, git.properties won’t exist on the classpath. Spring Boot skips creating GitProperties, and context startup fails with NoSuchBeanDefinitionException when instantiating SwaggerConfig.

Rather than making GitProperties? nullable and adding defensive branches to production code, add a lightweight fixture file at src/test/resources/git.properties. That keeps your production constructor clean and lets tests exercise info() directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# src/test/resources/git.properties
git.branch=File-Upload
git.build.host=MacBook-Pro.local
git.build.user.email=user@example.com
git.build.user.name=Namju Kim
git.build.version=0.0.1-SNAPSHOT
git.closest.tag.commit.count=
git.closest.tag.name=
git.commit.id=e0635482080626111ba16e5d1987f731d6fbe3be
git.commit.id.abbrev=e063548
git.commit.id.describe=
git.commit.message.full=cicd\: lint\n
git.commit.message.short=cicd\: lint
git.commit.time=2025-03-09T22\:23\:32+0900
git.commit.user.email=user@example.com
git.commit.user.name=Namju Kim
git.dirty=true
git.remote.origin.url=https\://github.com/cmsong111/Wanted-PreOnBoarding-Backend-Challenge.git
git.tags=
git.total.commit.count=49

2. GitHub Actions shallow clones (fetch-depth: 0)

actions/checkout defaults to fetch-depth: 1, which pulls only the latest commit. Under a shallow clone, Git tags and total commit counts are missing from the generated git.properties. Set fetch-depth: 0 in your workflow so the plugin sees the full history:

1
2
3
4
5
# .github/workflows/ci-cd.yaml
steps:
  - uses: actions/checkout@v7
    with:
      fetch-depth: 0

3. Disabling Swagger exposure in production

Commit messages, branch names, developer emails, and repository URLs are internal metadata. Disable Swagger by default in your production profile (application-prod.yml) and toggle it only via an explicit environment variable if needed:

1
2
3
4
5
6
# src/main/resources/application-prod.yml
springdoc:
  api-docs:
    enabled: ${SWAGGER_ENABLED:false}
  swagger-ui:
    enabled: ${SWAGGER_ENABLED:false}

Turning off swagger-ui.enabled alone is not enough—/v3/api-docs will still serve the raw OpenAPI JSON containing your commit metadata. Always disable api-docs.enabled alongside it.

Checklist and references

Wiring gradle-git-properties and GitProperties into SwaggerConfig gives everyone on the team immediate visibility into what’s deployed on dev and staging servers. Before rolling this out, verify these four items:

  • Add src/test/resources/git.properties so IDE and CI test runs don’t fail with NoSuchBeanDefinitionException.
  • Set fetch-depth: 0 in GitHub Actions if you rely on tags or commit counts.
  • Configure an explicit timezone (TZ env var or ZoneId) if your containers run in UTC.
  • Disable both springdoc.swagger-ui.enabled and springdoc.api-docs.enabled in application-prod.yml.
Gradle plugin for `git.properties` file generation - n0mer/gradle-git-properties
Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the health endpoint provides basic application health information.
This post is licensed under CC BY 4.0 by the author.