1. 概要

このチュートリアルでは、Gitリポジトリ情報をMavenで構築されたSpring Bootベースのアプリケーションに挿入する方法を示します。

これを行うために、maven-git-commit-id-pluginを使用します。これはこの目的のためだけに作成された便利なツールです。

2. Mavenの依存関係

プラグインをに追加しましょう私たちのセクション pom.xml 私たちのプロジェクトのファイル:

<plugin>
    <groupId>pl.project13.maven</groupId>
    <artifactId>git-commit-id-plugin</artifactId>
    <version>2.2.1</version>
</plugin>

最新バージョンはここにあります。 このpluginには少なくとも3.1.1バージョンのMavenが必要であることに注意してください。

このプラグインには、異なるリポジトリ座標で利用可能な、より新しいバージョン(5.x以降)があります。 ただし、そのバージョンにはJava11が必要です。 Java8ベースラインを持つSpring Boot2.xを使用してサンプルアプリケーションを開発するため、古いバージョンのプラグインを使用する必要があります。 これにより、SpringBootとgit-commit-id-pluginの間の互換性を維持できます。

3. 構成

プラグインには、その機能を拡張する多くの便利なフラグと属性があります。 このセクションでは、それらのいくつかについて簡単に説明します。 それらすべてを知りたい場合は、maven-git-commit-id-pluginのページにアクセスしてください。例に直接進みたい場合は、セクション4に進んでください。 。

次のスニペットには、プラグイン属性の例が含まれています。 必要に応じて、 セクションで指定してください。

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. プロパティファイルの生成

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コントローラーを作成しましょう。

SpringBootを使用してサンプルアプリを作成します。 Spring Bootアプリケーションのセットアップ方法がわからない場合は、紹介記事Spring BootWebアプリケーションの構成を参照してください。

このアプリは、アプリケーションCommitIdControllerの2つのクラスで構成されます。

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;
    }
}

アプリケーションのルートを構成することに加えて、プラグインによって生成されたプロパティファイルにアクセスできるように、 PropertyPlaceHolderConfigurerbeanを作成しました。

また、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ファイルを含める必要があります。 これを実現するには、2つのオプションがあります。

1つ目は、ファイルを生成するプラグインに任せることです。 これを指定するには、generateGitPropertiesFile構成プロパティにtrue値を設定します。

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

2番目のオプションは、git.propertiesファイルをresourcesフォルダーに含めることです。 プロジェクトで使用するエントリのみを含めることができます。

# 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. SpringBootActuatorとの統合

SpringActuatorでプラグインを簡単に使用できます。

ドキュメントで読むことができるように、 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 の基本的な使用方法を示し、プラグインによって生成されたプロパティを利用する単純なSpringBootアプリケーションを作成しました。

提示された構成は、使用可能なすべてのフラグと属性を網羅しているわけではありませんが、このプラグインの使用を開始するために必要なすべての基本を網羅しています。

コード例はGithubにあります。