Spring › Feature

gradle-git-properties로 Swagger UI에 마지막 커밋 정보 표시하기

Spring Boot에서 gradle-git-properties 플러그인과 GitProperties 빈을 활용해 Swagger UI에 마지막 커밋 해시, 브랜치, 커밋 링크, 배포 시각을 표시하는 방법과 테스트·CI·운영 주의사항을 정리합니다.

gradle-git-properties로 Swagger UI에 마지막 커밋 정보 표시하기

개발 서버 배포 후 프론트엔드와 협업할 때 “어느 커밋이 반영됐는지” 즉시 확인할 수 있도록, gradle-git-properties와 GitProperties 빈으로 Swagger UI 상단에 마지막 커밋 정보를 표시하는 방법을 정리합니다.

기준 환경: Spring Boot 3.x, Kotlin, Java 21, Gradle Kotlin DSL, springdoc-openapi-starter-webmvc-ui

도입 배경: 배포 커밋 확인 비용 줄이기

API를 수정해 개발 서버에 배포한 뒤 프론트엔드와 연동하다 보면 “방금 머지한 커밋이 올라갔는지”, “현재 브랜치가 main인지” 확인하는 질문이 반복됩니다. 매번 GitHub Actions 로그나 컨테이너 태그를 확인하는 대신, 협업 대상자가 가장 자주 여는 화면에 배포 정보를 노출하는 편이 효율적입니다.

확인 방식장점단점
CI 로그 / 서버 확인추가 구현 불필요프론트엔드·QA가 직접 확인하기 번거로움
/actuator/info모니터링 도구 연동에 적합API 문서와 화면이 분리됨
Swagger UI InfoAPI 화면에서 커밋 링크·시각 즉시 확인운영 노출 제어·테스트 리소스 관리 필요

Swagger UI 최상단 Info 영역에 커밋 해시, 브랜치, 커밋 링크, 커밋 시각, 버전을 표시하면 별도 문의 없이 배포 상태를 검증할 수 있습니다.

gradle-git-properties 플러그인 설정과 내부 동작

빌드 시점의 Git 메타데이터를 애플리케이션으로 넘기려면 build.gradle.kts에 com.gorylenko.gradle-git-properties 플러그인을 추가합니다.

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")
}

이 설정만으로 GitProperties 빈이 자동 등록되는 내부 흐름은 다음과 같습니다.

  1. 빌드 시 리소스 생성: generateGitProperties 태스크가 processResources에 연결되어 .git 메타데이터를 읽어 build/resources/main/git.properties를 생성합니다.
  2. 조건부 자동 구성: ProjectInfoAutoConfiguration이 @ConditionalOnResource(resources = "${spring.info.git.location:classpath:git.properties}") 조건으로 파일 존재 시 GitProperties 빈을 자동 등록합니다.
  3. 접두사 자동 제거: GitProperties는 git. 접두사를 제거해 보관하므로 gitProperties.get("commit.message.full")처럼 조회할 수 있습니다.

SwaggerConfig에 커밋 정보 표시하기

자동 등록된 GitProperties 빈을 SwaggerConfig에 주입받아 OpenAPI Info의 description과 version을 구성합니다.

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 설정 */
@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>JWT Token을 발급받아 Header에 넣어 요청합니다.</p>
                <p>Bearer [JWT Token 값]</p>
                """.trimIndent(),
            )
            .scheme("bearer")
            .bearerFormat("JWT")
    }

    /**
     * OpenAPI Info
     */
    private fun info(): Info {
        // Timezone 적용
        val zonedDateTime: ZonedDateTime = ZonedDateTime.ofInstant(gitProperties.commitTime, ZonedDateTime.now().zone)
        val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 a hh:mm")

        // Commit URL
        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>You can See Full Source Code at <a target="_blank" href="${gitProperties.get("remote.origin.url")}">Github</a></p>
                <p>API Document is generated by Swagger</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 = "cmsong111@gmail.com"
            }
            version = gitProperties.get("build.version")
        }
    }

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

gitProperties.commitTime은 Instant이므로 ZonedDateTime.ofInstant(...)로 변환해 포맷팅합니다. Docker 컨테이너 기본 타임존이 UTC라면 TZ=Asia/Seoul을 설정하거나 ZoneId.of("Asia/Seoul")을 명시해야 한국 시각으로 출력됩니다. remote.origin.url의 .git을 /commit/${gitProperties.shortCommitId}로 치환하면 클릭 한 번으로 GitHub 커밋 diff로 이동합니다.

테스트와 CI/CD, 운영 환경 주의사항

1. 테스트 환경의 NoSuchBeanDefinitionException 방지

IDE에서 processResources 없이 테스트를 실행하면 git.properties가 없어 GitProperties 빈이 등록되지 않고, SwaggerConfig 주입 단계에서 NoSuchBeanDefinitionException이 발생합니다.

GitProperties? nullable 주입 대신 src/test/resources/git.properties 더미 파일을 두면 프로덕션 코드에 null 분기를 넣지 않고도 info() 로직까지 그대로 검증할 수 있습니다.

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=cmsong111@naver.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=cmsong111@naver.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 Clone(fetch-depth: 0)

actions/checkout 기본값은 fetch-depth: 1(얕은 클론)이라 태그와 전체 커밋 수가 누락됩니다. 체크아웃 단계에 fetch-depth: 0을 지정해 전체 히스토리를 가져옵니다.

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

3. 프로덕션 환경 Swagger 노출 제어

커밋 메시지·브랜치명·이메일·저장소 URL은 내부 정보이므로 운영 프로필(application-prod.yml)에서 기본 비활성화합니다.

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}

주의: swagger-ui.enabled만 끄면 /v3/api-docs JSON에 커밋 정보가 그대로 노출됩니다. api-docs.enabled도 반드시 함께 꺼야 합니다.

정리

gradle-git-properties와 GitProperties 빈을 SwaggerConfig에 연결하면 별도 소통 없이도 Swagger UI에서 현재 서버의 배포 커밋을 즉시 확인할 수 있습니다. src/test/resources/git.properties, CI의 fetch-depth: 0, 운영 프로필의 SWAGGER_ENABLED:false 제어를 함께 적용하면 안전하게 운영할 수 있습니다.

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.