如何以编程方式将内容添加到
Spring Boot中的
/info
端点? 文档指出,通过使用 /health
接口,这对于 HealthIndicator
端点来说是可能的。 /info
端点也有一些东西吗?
我想在那里添加操作系统名称和版本以及其他运行时信息。
在 Spring Boot 1.4 中,您可以声明
InfoContributer
beans 以使这一切变得更容易:
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example",
Collections.singletonMap("key", "value"));
}
}
接受的答案实际上破坏了InfoEndpoint并且没有添加到它。
我发现 add 到信息的一种方法是,在
@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));
}
执行您想要的操作的一种方法(如果您需要显示完全自定义的属性)是声明一个 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);
}
从上面的代码中可以看到,地图可以包含您需要的任何信息。
如果您想要显示的数据可以通过环境检索并且不是自定义的,则无需覆盖
InfoEndpoint
bean,而只需将属性添加到前缀为 info
的属性文件中即可
。评估操作系统名称的一个示例如下:
info.os = ${os.name}
在上面的代码中,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));
}
上面的代码将完全覆盖最终在
/info
中的默认信息。
为了解决这个问题,可以添加以下 bean
@Bean
public MapInfoContributor mapInfoContributor() {
return new MapInfoContributor(new HashMap<String, Object>() {{
put("test", "value");
}});
}
应该可以在 ApplicationListener 中添加自定义 PropertySource 以将自定义 info.* 属性添加到环境中(请参阅此答案以获取示例:如何以编程方式覆盖 Spring-boot application.properties )