Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – Spring Top – Temp – Non-Geo (Lightrun)

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

>> LEARN SPRING
NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

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

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

2. Maven Dependencies

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

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

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.

3. Configuration

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.

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

3.1. Missing Repository

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

<failOnNoGitDirectory>false</failOnNoGitDirectory>

3.2. Git Repository Location

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

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

3.3. Output File

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

For more generous logging use:

<verbose>true</verbose>

3.5. Properties File Generation

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

<generateGitPropertiesFile>false</generateGitPropertiesFile>

3.6. Properties' Prefix

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

<prefix>git</prefix>

3.7. Only for Parent Repository

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

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

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

3.9. Properties Inclusion

Including only specified data is also possible:

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

4. Sample Application

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

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.

Our app will consist of 2 classes: Application and CommitIdController

4.1. Application

CommitIdApplication will serve as a root of our application:

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

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

4.2. Controller

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

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.

4.3. Maven Entry

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.

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:

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

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.

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

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

5. Integration With Spring Boot Actuator

You can use the plugin with Spring Actuator easily.

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:

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

6. Conclusion

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.

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.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE
Maven footer banner
Comments are closed on this article!