如何以编程方式在spring boot中向/ info端点添加内容?

Wim*_*uwe 21 spring-boot

如何以编程方式/infoSpring Boot中向端点添加内容?该文件指出,这是可能的/health,通过使用端点HealthIndicator接口./info端点也有什么东西吗?

我想在那里添加操作系统名称和版本以及其他运行时信息.

Wim*_*uwe 27

在Spring Boot 1.4中,您可以声明InfoContributerbean以使其更容易:

@Component
public class ExampleInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("example",
                Collections.singletonMap("key", "value"));
    }

}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#production-ready-application-info-custom.


geo*_*and 9

实现所需的一种方法(如果您需要显示完全自定义的属性)是声明一个InfoEndpoint类型的bean,它将覆盖默认值.

@Bean
public InfoEndpoint infoEndpoint() {
     final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
     map.put("test", "value"); //put whatever other values you need here
     return new InfoEndpoint(map);
}
Run Code Online (Sandbox Code Playgroud)

从上面的代码中可以看出,地图可以包含您需要的任何信息.

如果要显示的数据可以由环境检索而不是自定义,则不需要覆盖InfoEndpointbean,但只需将属性添加到属性文件中,前缀为info.评估OS名称的一个示例如下:

info.os = ${os.name}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,Spring Boot将在返回/info端点中的属性之前评估右侧表达式.

最后要注意的是,/env端点中已有大量环境信息

更新

正如@shabinjo所指出的,在较新的Spring Boot版本中,没有InfoEndpoint接受地图的构造函数.但是,您可以使用以下代码段:

@Bean
public InfoEndpoint infoEndpoint() {
     final Map<String, Object> map = new LinkedHashMap<String, Object>();
     map.put("test", "value"); //put whatever other values you need here
     return new InfoEndpoint(new MapInfoContributor(map));
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将完全覆盖最终的默认信息/info.要克服这个问题,可以添加以下bean

@Bean
public MapInfoContributor mapInfoContributor() {
    return new MapInfoContributor(new HashMap<String, Object>() {{
        put("test", "value");
    }});
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ond 8

接受的答案实际上破坏了InfoEndpoint并且没有添加它.

我发现添加到信息中的@Configuration一种@Autowired方法是,在类中添加一个方法,该方法将遵循info.*约定的额外属性添加到环境中.然后InfoEndpoint在调用时将它们拾起.

您可以执行以下操作:

@Autowired
public void setInfoProperties(ConfigurableEnvironment env) {
    /* These properties will show up in the Spring Boot Actuator /info endpoint */
    Properties props = new Properties();

    props.put("info.timeZone", ZoneId.systemDefault().toString());

    env.getPropertySources().addFirst(new PropertiesPropertySource("extra-info-props", props));
}
Run Code Online (Sandbox Code Playgroud)