如何将Java 8的CompositeHealthIndicator健康检查代码迁移至Java 17
适配Java 17的健康检查代码改写方案
核心改动说明
- 过时的
CompositeHealthIndicator替换为CompositeHealthContributor,通过其静态工厂方法fromMap()创建实例 - 过时的
OrderedHealthAggregator替换为DefaultHealthAggregator(Spring Boot默认的健康聚合器) - 调整依赖注入的类型,从
HealthIndicator统一为HealthContributor(HealthIndicator是HealthContributor的子接口) - 简化状态判断逻辑,直接使用
Status.UP常量对比,避免字符串操作
改写后的完整代码
import org.springframework.boot.actuate.health.CompositeHealthContributor; import org.springframework.boot.actuate.health.DefaultHealthAggregator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthContributor; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.Status; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; public class ApiHealthIndicator implements HealthIndicator { private final CompositeHealthContributor compositeHealthContributor; private final DefaultHealthAggregator healthAggregator; private final String healthCheckCode; // 假设该字段已在类中定义 @Autowired public ApiHealthIndicator(ObjectProvider<Map<String, HealthContributor>> healthContributors, DefaultHealthAggregator healthAggregator) { // 获取可用的健康贡献者Map,为空时返回空Map Map<String, HealthContributor> availableHealthContributors = healthContributors.getIfAvailable(Map::of); this.compositeHealthContributor = CompositeHealthContributor.fromMap(availableHealthContributors); this.healthAggregator = healthAggregator; } @Override public Health health() { // 收集所有健康指标的状态,进行聚合 Map<String, Health> healths = new HashMap<>(); compositeHealthContributor.forEach((name, contributor) -> { if (contributor instanceof HealthIndicator indicator) { healths.put(name, indicator.health()); } }); Health aggregatedHealth = healthAggregator.aggregate(healths.values()); // 判断聚合后的状态 if (Status.UP.equals(aggregatedHealth.getStatus())) { return Health.status(healthCheckCode).build(); } return Health.down().build(); } }
额外说明
- 如果不需要自定义聚合逻辑,可省略
DefaultHealthAggregator的注入,直接遍历CompositeHealthContributor收集状态后自行判断,但官方推荐使用标准聚合器保证逻辑一致性。 - 若使用Spring Boot 3.x(适配Java 17的推荐版本),
HealthContributor系列API是官方指定的替代方案,完全兼容新特性。 - 代码中
healthCheckCode字段假设已在类中定义,若未定义需补充对应字段声明或赋值逻辑。
内容的提问来源于stack exchange,提问作者Chandrahasa Reddy D
相关产品推荐
相关产品推荐

