spring-boot - 扩展 GitInfoContributor 以添加属性?

标签 spring-boot spring-boot-actuator

在我发现 Spring Boot 的 Info Actuator 几乎包含我想要发布的所有内容之前,我制作了一些元端点以确保我可以访问构建和 Git 信息,这些信息在尝试验证以下内容时会有所帮助:

  • “是否部署了正确的版本?”
  • “这是谁建的?”
  • “它是什么时候 build 的?”
  • “这是基于哪个 git commit?”

在那之后,我确实着手发现了 Info 执行器,它几乎为我回答了所有这些问题,但是我想添加 Git 信息中的一些内容——主要是提交消息和脏标志。

如果我打开完整的 git 元数据,我会查看输出:

management.info.git.mode=full

但是......这增加了更多的信息,其中大部分我并不关心,所以它比我真正想要的要多。

我想做的是获取 GitInfoContributor 并扩展/替换它,但我不太确定该怎么做。添加我自己的贡献者很容易,但是如果我添加我自己的贡献者并调用 builder.withDetails("git"),就像这样:

package ca.cpp.api.submitapi.config

import org.springframework.boot.actuate.info.Info
import org.springframework.boot.actuate.info.InfoContributor
import org.springframework.boot.info.GitProperties
import org.springframework.stereotype.Component

@Component
class CustomGitInfoContributor(private val properties: GitProperties): InfoContributor {
    override fun contribute(builder: Info.Builder?) {
        builder?.withDetail("git",mapOf("dirty" to properties.get("dirty"))
    }
}

这取代了整套 git 属性,与此同时,我认为核心 GitInfoContributor 仍然存在,仍然提供我要丢弃的信息。

是否有一种合理的方法来仅添加我想要的元素,或者使用我自己的贡献者可以将其信息与“git”下已有的信息合并,或者通过某种方式扩展/替换现有的 GitInfoContributor?

最佳答案

在“git”部分下添加新元素的最简单方法是扩展 GitInfoContributor

Kotlin :

@Component
class CustomGitInfoContributor @Autowired
constructor(properties: GitProperties) : GitInfoContributor(properties) {

    override fun contribute(builder: Info.Builder) {
        val map = generateContent()
        map["dirty"] = properties.get("dirty")
        builder.withDetail("git", map)
    }
}

Java:

@Component
public class CustomGitInfoContributor extends GitInfoContributor {

  @Autowired
  public CustomGitInfoContributor(GitProperties properties) {
    super(properties);
  }

  @Override
  public void contribute(Info.Builder builder) {
    Map<String, Object> map = generateContent();
    map.put("dirty", getProperties().get("dirty"));
    builder.withDetail("git", map);
  }
}

此代码将在默认 git 信息之后添加脏部分,例如{"git":{"commit":{"time":"2018-11-03T15:22:51Z","id":"caa2ef0"},"branch":"master","dirty":"真"}}

如果您不想生成默认的 git 信息部分,只需删除 generateContent() 调用即可。

关于spring-boot - 扩展 GitInfoContributor 以添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52881224/

相关文章:

java - 如何在同一个Tomcat上部署多个具有外部配置的Spring boot应用程序?

spring-boot - 无法连接到本地运行在Docker上的Spring Boot应用

java - Http 响应内容类型为 json。 "Invalid mime type"错误

java - 为什么我的计划作业没有并行执行

spring - 如何配置 Spring Boot Security 以便仅允许用户更新自己的配置文件

spring-boot - "Did not find handler method for"使用 Spring Boot Actuator 记录消息

java - 阻止 Spring Boot 应用程序关闭,直到所有当前请求都完成

java - 使用 java 函数从 Spring boot 调用 Spring 执行器/重启端点

java - Spring Boot Actuator - 自定义端点

spring - 如何从 Actuator/metrics 端点中排除 Hystrix Metrics?