知識庫 / Spring RSS 訂閱

將 Git 信息注入 Spring

Spring
HongKong
2
02:47 PM · Dec 06 ,2025

1. 概述

本教程將演示如何將 Git 倉庫信息注入到基於 Maven 構建的 Spring Boot 應用中。

為了實現此目的,我們將使用 maven-git-commit-id-plugin – 一個專門為此目的而設計的實用工具。

2. Maven 依賴

讓我們為我們的項目在 <plugins> 部分添加一個插件:

<plugins>
  <!--  這裏添加插件配置 -->
</plugins>
<plugin>
    <groupId>pl.project13.maven</groupId>
    <artifactId>git-commit-id-plugin</artifactId>
    <version>2.2.1</version>
</plugin>

您可以在這裏找到最新版本:此處。請注意,該插件需要 Maven 3.1.1 或更高版本。

請注意,該插件有更晚移位版本(5.x 或更高版本)可在不同的座標下找到。但是,該版本需要 Java 11。由於我們將使用 Java 8 作為基礎,使用 Spring Boot 2.x 開發一個示例應用程序,因此我們需要使用插件的舊版本。這使我們能夠保持 Spring Boot 和 之間的兼容性。

3. 配置

該插件提供了許多方便的標誌和屬性,以擴展其功能。 在本部分,我們將簡要描述其中一些。 如果您想了解所有這些,請訪問 maven-git-commit-id-plugin 的 頁面,並且 <strong title="如果您想直接跳轉到示例,請查看第 4 節>如果您想直接跳轉到示例,請查看第 4 節

以下代碼片段包含插件屬性示例;請根據您的需要,在 configuration 節中指定它們。

3.1. 缺失倉庫

你可以配置它以忽略未找到 Git 倉庫時產生的錯誤:

<failOnNoGitDirectory>false</failOnNoGitDirectory>

3.2. Git 倉庫位置

如果需要指定自定義 .git 倉庫位置,請使用 dotGitDirectory 屬性:

<dotGitDirectory>${project.basedir}/submodule_directory/.git</dotGitDirectory>

3.3. 輸出文件

為了生成具有自定義名稱和/或目錄的屬性文件,請使用以下部分:

<generateGitPropertiesFilename>
    ${project.build.outputDirectory}/filename.properties
</generateGitPropertiesFilename>

3.4. 冗餘日誌

為了更詳細的日誌記錄,請使用:

<verbose>true</verbose>

3.5. 生成 Properties 文件

你可以禁用 git.properties 文件的創建。

<generateGitPropertiesFile>false</generateGitPropertiesFile>

3.6. 屬性前綴

如果需要指定自定義屬性前綴,請使用:

<prefix>git</prefix>

3.7. 僅限父倉庫

當處理帶有子模塊的項目時,設置此標誌可確保插件僅適用於父倉庫。

<runOnlyOnce>true</runOnlyOnce>

3.8. 屬性排除

您可能需要排除一些敏感數據,例如倉庫用户信息:

<excludeProperties>
    <excludeProperty>git.user.*</excludeProperty>
</excludeProperties>

3.9. 屬性包含

只包含指定的數據也是可行的:

<includeOnlyProperties>    
    <includeOnlyProperty>git.commit.id</includeOnlyProperty>
</includeOnlyProperties>

4. 示例應用程序

讓我們創建一個示例 REST 控制器,該控制器將返回有關我們項目的基本信息。

我們將使用 Spring Boot 創建示例應用程序。如果您不瞭解如何設置 Spring Boot 應用程序,請參閲入門文章:配置 Spring Boot Web 應用程序。

我們的應用程序將包含 2 個類:ApplicationCommitIdController

4.1. 應用

CommitIdApplication 將作為我們應用程序的根目錄:

@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
public class CommitIdApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(CommitIdApplication.class, args);
    }
 
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propsConfig 
          = new PropertySourcesPlaceholderConfigurer();
        propsConfig.setLocation(new ClassPathResource("git.properties"));
        propsConfig.setIgnoreResourceNotFound(true);
        propsConfig.setIgnoreUnresolvablePlaceholders(true);
        return propsConfig;
    }
}

除了配置應用程序的根目錄,我們還創建了 PropertyPlaceHolderConfigurer Bean,以便我們能夠訪問插件生成的屬性文件。

我們還設置了一些標誌,以確保即使 Spring 無法解析 git.properties 文件,應用程序也能順利運行。

4.2. 控制器

@RestController
public class CommitInfoController {

    @Value("${git.commit.message.short}")
    private String commitMessage;

    @Value("${git.branch}")
    private String branch;

    @Value("${git.commit.id}")
    private String commitId;

    @RequestMapping("/commitId")
    public Map<String, String> getCommitId() {
        Map<String, String> result = new HashMap<>();
        result.put("Commit message",commitMessage);
        result.put("Commit branch", branch);
        result.put("Commit id", commitId);
        return result;
    }
}

正如您所見,我們正在將 Git 屬性注入到類字段中。

要查看所有可用的屬性,請參考 git.properties文件或作者的 GitHub 頁面

我們還創建了一個簡單的端點,在 HTTP GET 請求下,將響應一個包含注入值的 JSON

4.3. Maven 引入

我們將首先設置插件執行步驟以及我們認為有用的任何其他配置屬性:

<plugin>
    <groupId>pl.project13.maven</groupId>
    <artifactId>git-commit-id-plugin</artifactId>
    <version>2.2.1</version>
    <executions>
        <execution>
            <id>get-the-git-infos</id>
            <goals>
                <goal>revision</goal>
            </goals>
        </execution>
        <execution>
            <id>validate-the-git-infos</id>
            <goals>
                <goal>validateRevision</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <!-- ... -->
    </configuration>
</plugin>

為了確保我們的代碼能夠正常工作,我們需要在類路徑中生成一個 git.properties 文件。為了實現這一點,我們有以下兩種選擇。

第一種方法是讓插件自動生成該文件。可以通過設置 generateGitPropertiesFile 配置屬性為 true 來實現:

<configuration>
    <generateGitPropertiesFile>true</generateGitPropertiesFile>
</configuration>

第二種選項是在 resources 文件夾中自行添加一個 git.properties 文件。我們可以只包含我們項目中使用到的條目:

# git.properties
git.tags=${git.tags}
git.branch=${git.branch}
git.dirty=${git.dirty}
git.remote.origin.url=${git.remote.origin.url}
git.commit.id=${git.commit.id}
git.commit.id.abbrev=${git.commit.id.abbrev}
git.commit.id.describe=${git.commit.id.describe}
git.commit.id.describe-short=${git.commit.id.describe-short}
git.commit.user.name=${git.commit.user.name}
git.commit.user.email=${git.commit.user.email}
git.commit.message.full=${git.commit.message.full}
git.commit.message.short=${git.commit.message.short}
git.commit.time=${git.commit.time}
git.closest.tag.name=${git.closest.tag.name}
git.closest.tag.commit.count=${git.closest.tag.commit.count}
git.build.user.name=${git.build.user.name}
git.build.user.email=${git.build.user.email}
git.build.time=${git.build.time}
git.build.host=${git.build.host}
git.build.version=${git.build.version}

Maven 將會用適當的值替換佔位符。

注意:某些 IDE 可能無法很好地與此插件配合使用,並且在定義屬性時(如上所述),可能會在啓動時拋出“循環佔位符引用”錯誤。

在啓動後並請求 localhost:8080/commitId,您將看到一個結構類似於以下 JSON 文件的文件:

{
    "Commit id":"7adb64f1800f8a84c35fef9e5d15c10ab8ecffa6",
    "Commit branch":"commit_id_plugin",
    "Commit message":"Merge branch 'master' into commit_id_plugin"
}

5. 與 Spring Boot Actuator 集成

您可以使用該插件輕鬆地與 Spring Actuator 集成。

如您在 文檔 中所見,GitInfoContributor 將在可用時獲取 git.properties 文件。因此,默認插件配置下,調用 /info 端點時,將返回 Git 信息。

{
  "git": {
    "branch": "commit_id_plugin",
    "commit": {
      "id": "7adb64f",
      "time": "2016-08-17T19:30:34+0200"
    }
  }
}

6. 結論

在本教程中,我們演示了使用 maven-git-commit-id-plugin 的基本用法,並創建了一個簡單的 Spring Boot 應用,該應用利用插件生成的屬性。

所展示的配置並未涵蓋所有可用的標誌和屬性,但它涵蓋了使用該插件所需的所有基本內容。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.