1. 概述
Spring Boot 項目 提供功能,幫助創建獨立的基於 Spring 的應用程序,並支持雲原生開發。因此,它是一個對 Spring 框架的有用擴展。
有時,我們可能不想使用 Spring Boot,例如在將 Spring 框架集成到 Jakarta EE 應用程序時,但我們仍然希望從諸如指標和健康檢查之類的生產級功能中受益,這些功能被稱為“可觀測性”。(可以在文章“Spring Boot 3 中的可觀測性”中找到更多信息。)
可觀測性功能由 Spring Boot Actuator 提供,它是 Spring Boot 的一個子項目。 在本文中,我們將瞭解如何將 Actuator 集成到不使用 Spring Boot 的應用程序中。
2. 項目配置
當排除 Spring Boot 時,我們需要處理應用程序打包和服務器運行時配置,並且需要手動進行 外部化配置。 Spring Boot 提供的這些功能在我們的基於 Spring 的應用程序中是不必要的。 此外,雖然我們確實需要項目依賴項,但不能使用 Spring Boot 的 Starter 依賴項(例如,spring-boot-starter-actuator)。 除此之外,還需要嚮應用程序上下文添加必要的 Bean。
我們可以手動完成這些操作,也可以使用自動配置。 由於 Actuator 的配置非常複雜且未詳細記錄,我們應該優先使用自動配置。 這是我們從 Spring Boot 中獲得的唯一一部分,因此我們不能完全排除 Spring Boot。
2.1. 添加項目依賴
為了集成 Actuator,我們需要 spring-boot-actuator-autoconfigure 依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<version>3.0.6</version>
</dependency>這還將包含 spring-boot-actuator、spring-boot 和 spring-boot-autoconfigure 作為傳遞依賴。
2.2. 啓用自動配置
然後,我們啓用自動配置。這很容易通過在應用程序的配置中添加 @EnableAutoConfiguration 來完成:
@EnableAutoConfiguration
// ... @ComponentScan, @Import or any other application configuration
public class AppConfig {
// ...
}我們應該意識到,這可能會影響整個應用程序,因為這也會自動配置框架的其他部分,如果類路徑中包含更多的自動配置類,則會發生這種情況。
2.3. 啓用端點
默認情況下,僅啓用健康檢查端點。 Actuator 的自動配置類使用配置屬性。 例如,<em >WebEndpointAutoConfiguration</em > 使用 <em >WebEndpointProperties</em >,這些屬性映射到以 <em >management.endpoints.web</em > 前綴命名的屬性。 要啓用所有端點,我們需要……
management.endpoints.web.exposure.include=*這些屬性必須對上下文可用——例如,通過將它們放入 application.properties 文件中,並使用 @PropertySource 註解我們的配置類:
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
// ... @ComponentScan, @Import or any other application configuration
public class AppConfig {
}2.4. 測試項目配置
現在,我們準備調用 actuator 端點。可以通過以下屬性啓用健康詳情:
management.endpoint.health.show-details=always我們還可以實現自定義健康檢查端點:
@Configuration
public class ActuatorConfiguration {
@Bean
public HealthIndicator sampleHealthIndicator() {
return Health.up()
.withDetail("info", "Sample Health")
::build;
}
}向 “{url_to_project}/actuator/health” 發起調用,將會產生如下輸出:
3. 結論
在本教程中,我們學習瞭如何在非 Spring Boot 應用中集成 Spring Boot Actuator。