Spring - 在自定义健康端点上显示 git 提交 ID

作者:编程家 分类: spring 时间:2025-05-30

使用Spring自定义健康端点显示Git提交ID是一种常见的需求。通过在应用程序的健康端点中显示Git提交ID,我们可以方便地了解当前运行的应用程序的版本信息。在本文中,我们将介绍如何使用Spring实现这一功能,并提供相应的代码示例。

首先,我们需要添加Spring Boot Actuator依赖到我们的项目中。在pom.xml文件中添加以下依赖项:

xml

org.springframework.boot

spring-boot-starter-actuator

接下来,我们需要创建一个自定义的健康端点类,用于显示Git提交ID。我们可以通过实现`HealthIndicator`接口来创建自定义的健康端点。在这个类中,我们需要使用`GitProperties`来获取Git提交ID。下面是一个简单的示例:

java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.actuate.health.Health;

import org.springframework.boot.actuate.health.HealthIndicator;

import org.springframework.boot.info.GitProperties;

import org.springframework.stereotype.Component;

@Component

public class GitCommitHealthIndicator implements HealthIndicator {

private final GitProperties gitProperties;

@Autowired

public GitCommitHealthIndicator(GitProperties gitProperties) {

this.gitProperties = gitProperties;

}

@Override

public Health health() {

String commitId = gitProperties.getShortCommitId();

return Health.up().withDetail("git.commit.id", commitId).build();

}

}

在上面的代码中,我们通过构造函数注入了`GitProperties`,然后使用`getShortCommitId()`方法获取Git提交ID。最后,我们使用`Health`类的`up()`方法创建一个健康状态,并使用`withDetail()`方法添加Git提交ID的详细信息。

现在,我们已经创建了自定义的健康端点类,接下来我们需要在应用程序的配置文件中启用健康端点。在application.properties文件中添加以下配置:

management.endpoints.web.exposure.include=health

这样,健康端点就会在应用程序的/actuator/health路径下暴露出来。

现在,我们可以启动应用程序并访问/actuator/health端点来查看Git提交ID了。健康端点的响应中将包含我们添加的git.commit.id信息。

示例代码:

java

@RestController

public class HealthController {

@GetMapping("/actuator/health")

public ResponseEntity health() {

Health health = Health.status("UP").withDetail("git.commit.id", "123456").build();

return ResponseEntity.ok(health);

}

}

在上面的示例代码中,我们创建了一个简单的REST控制器,映射了/actuator/health路径,并返回了一个包含Git提交ID的健康状态。

通过以上步骤,我们成功地实现了在自定义健康端点上显示Git提交ID的功能。在应用程序的健康端点中,我们可以方便地查看当前运行的应用程序的版本信息。这对于应用程序的监控和管理非常有帮助。