有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Spring引导执行器中注册匿名HealthIndicators

这个链接writing_custom_healthindicators描述了如何注册自定义HealthIndicators,以便它们可以与弹簧引导执行器一起使用。链接中的示例使用@Component注册实现HealthIndicator接口的自定义类

但我正在创建匿名HealthIndicator实例。下面是如何创建这些匿名HealthIndicators实例的示例

        HealthIndicator healthIndicator = () -> {
            Health h;
            //custom code to instantiate Health object.
            return h;
        };
        //how to register h with Spring?

假设上面的代码位于for循环中,其中创建了许多HealthIndicators。如何向Spring注册它们,以便Spring引导执行器能够识别链接中提到的它们


共 (1) 个答案

  1. # 1 楼答案

    一种方法是提供自定义^{},如下所示:

    @Configuration
    class HealthConfig {
        @Bean
        HealthEndpoint healthEndpoint(Map<String, HealthIndicator> defaultIndicators){
            for(int i=0;i<10;i+=1){
                defaultIndicators.put("custom_indicator_" + i, ()-> Health.down().build());
            }
            return new HealthEndpoint(new OrderedHealthAggregator(), defaultIndicators);
        }
    }