You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何实现包含默认健康信息的自定义路径端点

Spring Boot Actuator 自定义健康端点实现方案

方案1:使用@Endpoint自定义端点(符合Actuator规范)

该方案在Actuator的端点体系内实现,可通过配置灵活修改路径,同时保留Actuator端点的统一管理能力。

  • 核心思路:直接注入系统原生的HealthEndpoint实例,调用其方法即可获取默认/health端点的全部返回数据,再拼接自定义内容后返回,同时通过路径映射配置脱离/health前缀。

代码示例

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@Component
@Endpoint(id = "custom-health")
public class CustomHealthEndpoint {
    // 注入原生健康端点实例
    private final HealthEndpoint defaultHealthEndpoint;

    public CustomHealthEndpoint(HealthEndpoint defaultHealthEndpoint) {
        this.defaultHealthEndpoint = defaultHealthEndpoint;
    }

    @ReadOperation
    public Map<String, Object> getCustomHealthInfo() {
        Map<String, Object> result = new HashMap<>();
        // 塞入默认健康端点的全部返回数据
        result.put("baseHealth", defaultHealthEndpoint.health());
        // 自定义字段可随意添加
        result.put("serviceVersion", "v2.1.0");
        result.put("deployRegion", "cn-shanghai");
        result.put("businessStatus", "normal");
        return result;
    }
}

配置示例(application.yml)

management:
  endpoints:
    web:
      exposure:
        # 暴露自定义端点
        include: custom-health
      path-mapping:
        # 自定义路径,完全脱离/health规则,最终访问路径为 /actuator/app/health-status
        custom-health: /app/health-status
      # 如果要去掉/actuator前缀,可修改base-path
      # base-path: /
  endpoint:
    health:
      # 配置展示健康详情,和原生/health返回结构保持一致
      show-details: always

方案2:自定义Controller实现(路径完全自由)

如果不需要纳入Actuator端点的统一管理,想要完全自定义访问路径,直接用普通Controller实现即可,灵活性最高。

代码示例

import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomHealthController {
    private final HealthEndpoint defaultHealthEndpoint;

    public CustomHealthController(HealthEndpoint defaultHealthEndpoint) {
        this.defaultHealthEndpoint = defaultHealthEndpoint;
    }

    // 路径可完全自定义,不受Actuator规则限制
    @GetMapping("/internal/service/health")
    public Map<String, Object> getCustomHealth() {
        Map<String, Object> res = new HashMap<>();
        res.put("defaultHealthInfo", defaultHealthEndpoint.health());
        res.put("customCode", 0);
        res.put("customMsg", "服务运行正常");
        return res;
    }
}

注意事项

  • 如果原生/health端点配置了权限校验,需要同步给自定义端点配置对应权限,避免数据泄露
  • HealthEndpoint返回的Health实例本身是序列化友好的结构,无需额外转换可直接放入返回值中

内容的提问来源于stack exchange,提问作者user13566144

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:18:05