跳到主內容

【SpingBoot】取得git branch

出處 : https://blog.elliot.tw/?p=658

Spring Boot可以提供的Application資訊,參考以下連結

https://docs.spring.io/spring-boot/reference/actuator/endpoints.html#actuator.endpoints.info

ID Name Description Prerequisites
build BuildInfoContributor Exposes build information. META-INF/build-info.properties resource.
env EnvironmentInfoContributor Exposes any property from the Environment whose name starts with info.. None.
git GitInfoContributor Exposes git information. git.properties resource.
java JavaInfoContributor Exposes Java runtime information. None.
os OsInfoContributor Exposes Operating System information. None.

裡面提到了git,主要就是讀取git.properties

所以只要能產生git.properties

在此有兩種方式,一個是由Maven Plugin產生,另一個則由Gradle Plugin產生

Generate Git Information

Maven – git-commit-id-maven-plugin

      <plugin>
        <groupId>io.github.git-commit-id</groupId>
        <artifactId>git-commit-id-maven-plugin</artifactId>
        <version>6.0.0</version>
        <executions>
          <execution>
            <id>get-the-git-infos</id>
            <goals>
              <goal>revision</goal>
            </goals>
            <phase>initialize</phase>
          </execution>
        </executions>
        <configuration>
          <generateGitPropertiesFile>true</generateGitPropertiesFile>         <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
          <commitIdGenerationMode>full</commitIdGenerationMode>
        </configuration>
      </plugin>

Gradle – gradle-git-properties

    id("com.gorylenko.gradle-git-properties") version "2.4.1"

Spring Boot – Application Yaml

再來只要在managment裡加入info.git.enabled=true 即可

management:
  endpoints:
    web:
      exposure:
        include: '*'
  info:
    git:
      enabled: true
    java:
      enabled: true

Actuator Info

簡單透過actuator 提供的endpoint
http://localhost:8080/actuator/info

{
    "git": {
        "branch": "test/performance",
        "commit": {
            "id": "f95f360",
            "time": "2024-10-25T02:09:37Z"
        }
    },
    "build": {
        "artifact": "live-show",
        "name": "live-show",
        "time": "2024-10-25T02:54:21.087Z",
        "version": "2411.2.0",
        "group": "com.momo.app"
    },
    "java": {
        "version": "17.0.11",
        "vendor": {
            "name": "Amazon.com Inc.",
            "version": "Corretto-17.0.11.9.1"
        },
        "runtime": {
            "name": "OpenJDK Runtime Environment",
            "version": "17.0.11+9-LTS"
        },
        "jvm": {
            "name": "OpenJDK 64-Bit Server VM",
            "vendor": "Amazon.com Inc.",
            "version": "17.0.11+9-LTS"
        }
    }
}