Injecting Git Information Into Spring – 将Git信息注入到Spring中

最后修改: 2016年 8月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to show how to inject Git repository information into a Maven-built Spring Boot-based application.

在本教程中,我们将展示如何向基于Maven构建的Spring Boot应用程序注入Git仓库信息。

In order to do this we will use maven-git-commit-id-plugin – a handy tool created solely for this purpose.

为了做到这一点,我们将使用maven-git-commit-id-plugin–一个专门为此目的而创建的便捷工具。

2. Maven Dependencies

2.Maven的依赖性

Let’s add a plugin to a <plugins> section of our pom.xml file of our project:

让我们在我们项目的<plugins>文件的pom.xml部分添加一个插件。

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

You can find the latest version here. Keep in mind that this plugin requires at least 3.1.1 version of Maven.

您可以在这里找到最新版本。请记住,这个p插件至少需要3.1.1版的Maven.

Note, this plugin has a later relocated version (5.x or more recent) available at different repository coordinates. However, that version requires Java 11. As we’ll be developing a sample application using Spring Boot 2.x that has a Java 8 baseline, we’ll need to use the older version of the plugin. This allows us to maintain the compatibility between Spring Boot and git-commit-id-plugin.

注意,这个插件有一个较晚的重新定位的版本(5.x或更近的版本),在不同的存储库坐标中可以找到。但是,该版本需要Java 11。由于我们将使用具有Java 8基线的Spring Boot 2.x开发一个示例应用程序,我们需要使用该插件的旧版本。这使我们能够保持Spring Boot和git-commit-id-plugin之间的兼容性。

3. Configuration

3.配置

The plugin has many convenient flags and attributes which expand its functionality. In this section we are going to briefly describe some of them. If you want to get to know all of them, visit maven-git-commit-id-plugin’s page, and if you want to go straight to the example, go to section 4.

该插件有许多方便的标志和属性,可以扩展其功能。在本节中,我们将简要介绍其中一些。如果你想了解所有这些,请访问maven-git-commit-id-plugin的页面如果你想直接看例子,请看第4节

The following snippets contain examples of plugin attributes; specify them in a <configuration></configuration> section according to your needs.

下面的片段包含了插件属性的例子;根据你的需要在<configuration></configuration>部分指定它们。

3.1. Missing Repository

3.1.缺少存储库

You can configure it to omit errors if Git repository has not been found:

你可以配置它在没有找到Git仓库的情况下省略错误。

<failOnNoGitDirectory>false</failOnNoGitDirectory>

3.2. Git Repository Location

3.2.Git仓库的位置

If you want to specify custom .git repository location, use dotGitDirectory attribute:

如果你想指定自定义的.git仓库位置,使用dotGitDirectory属性。

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

3.3. Output File

3.3.输出文件

In order to generate properties file with a custom name and/or directory, use following section:

为了生成具有自定义名称和/或目录的属性文件,请使用以下部分。

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

3.4. Verbosity

3.4.动词

For more generous logging use:

为了更慷慨地记录,请使用。

<verbose>true</verbose>

3.5. Properties File Generation

3.5.属性文件的生成

You can turn off creation of a git.properties file:

你可以关闭git.properties文件的创建。

<generateGitPropertiesFile>false</generateGitPropertiesFile>

3.6. Properties’ Prefix

3.6.属性的前缀

If you want to specify a custom property prefix, use:

如果你想指定一个自定义的属性前缀,请使用。

<prefix>git</prefix>

3.7. Only for Parent Repository

3.7.仅适用于父存储库

When working with project with submodules, setting this flag makes sure, that plugin works only for parent repository:

当处理有子模块的项目时,设置这个标志可以确保该插件只对父版本库工作。

<runOnlyOnce>true</runOnlyOnce>

3.8. Properties Exclusion

3.8.属性排除

You might want to exclude some sensitive data like repository user info:

你可能想排除一些敏感数据,如存储库用户信息。

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

3.9. Properties Inclusion

3.9.属性包括

Including only specified data is also possible:

只包括指定的数据也是可能的。

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

4. Sample Application

4.应用样本

Let’s create a sample REST controller, which will return basic information about our project.

让我们创建一个REST控制器样本,它将返回关于我们项目的基本信息。

We will create the sample app using Spring Boot. If you don’t know how to set up a Spring Boot application, please see the introductory article: Configure a Spring Boot Web Application.

我们将使用Spring Boot创建示例应用程序。如果您不知道如何设置Spring Boot应用程序,请参见介绍性文章。配置Spring Boot Web应用程序

Our app will consist of 2 classes: Application and CommitIdController

我们的应用程序将由2个类组成。应用程序CommitIdController

4.1. Application

4.1.应用

CommitIdApplication will serve as a root of our application:

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

Besides configuring the root of our application, we created PropertyPlaceHolderConfigurer bean so that we are able to access properties file generated by the plugin.

除了配置我们应用程序的根,我们还创建了PropertyPlaceHolderConfigurerbean,这样我们就能够访问由插件生成的属性文件。

We also set some flags, so that application would run smoothly even if Spring could not resolve the git.properties file.

我们还设置了一些标志,这样即使Spring不能解决git.properties文件,应用程序也能顺利运行。

4.2. Controller

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

As you can see we are injecting Git properties into class fields.

正如你所看到的,我们正在将Git属性注入类的字段中。

To see all properties available refer to git.properties file or author’s Github page. We also created a simple endpoint which, on HTTP GET request, will respond with a JSON containing injected values.

要查看所有可用的属性,请参考git.properties文件或作者的Github 页面。我们还创建了一个简单的端点,在HTTP GET请求中,它将响应包含注入值的JSON

4.3. Maven Entry

4.3.Maven条目

We’ll first set up the execution steps to be carried out by the plugin, plus any other configuration property that we consider useful:

我们将首先设置插件要执行的执行步骤,加上我们认为有用的其他配置属性。

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

In order for our code to work properly, we need to end up with a git.properties file in our classpath. To achieve this, we have two options.

为了让我们的代码正常工作,我们需要在classpath中最终有一个git.properties文件。为了实现这一点,我们有两个选择。

The first one is to leave it up to the plugin to generate the file. We can specify this by setting the generateGitPropertiesFile configuration property a true value:

第一种是由插件来生成文件。我们可以通过将generateGitPropertiesFile配置属性设置为true值来指定。

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

The second option is to include a git.properties file in the resources folder ourselves. We can include only the entries that we’ll use in our project:

第二个选择是在资源文件夹中自己包含一个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 will replace the placeholders with the appropriate values.

Maven会用适当的值替换占位符。

Note: Some IDEs don’t work well with this plugin, and might throw a ‘circular placeholder reference’ error on bootstrap when we define the properties as we did above.

注意:有些IDE不能很好地使用这个插件,当我们像上面那样定义属性时,可能会在bootstrap上抛出 “循环占位符引用 “的错误。

After booting and requesting localhost:8080/commitId you can see a JSON file with a structure similar to the following:

启动并请求localhost:8080/commitId后,你可以看到一个JSON文件,其结构类似于以下内容。

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

5. Integration With Spring Boot Actuator

5.与Spring Boot Actuator的集成

You can use the plugin with Spring Actuator easily.

你可以轻松地将该插件与Spring Actuator一起使用。

As you can read in the documentation, GitInfoContributor will pick git.properties file up if available. So, with default plugin configuration, Git information will be returned when calling /info endpoint:

正如你可以在文档中读到的那样,GitInfoContributor将挑选git.properties文件,如果有的话。因此,在默认的插件配置下,当调用/info端点时,将返回Git信息。

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

6. Conclusion

6.结论

In this tutorial we showed the basic of using maven-git-commit-id-plugin and created a simple Spring Boot application, which makes use of properties generated by the plugin.

在本教程中,我们展示了使用maven-git-commit-id-plugin的基本情况,并创建了一个简单的Spring Boot应用程序,该程序利用了该插件生成的属性。

Presented configuration does not cover all available flags and attributes, but it covers all basics necessary to start working with this plugin.

所介绍的配置并不包括所有可用的标志和属性,但它涵盖了开始使用该插件所需的所有基本要素。

You can find code examples on Github.

你可以在Github上找到代码示例。