沒有彈簧引導的彈簧引導執行器
一、概述
Spring Boot 項目提供的功能有助於創建獨立的基於 Spring 的應用程序並支持雲原生開發。因此,它是對 Spring Framework 的擴展,非常有用。
有時,我們不想使用 Spring Boot,例如將 Spring Framework 集成到 Jakarta EE 應用程序中時,但是,我們仍然希望從指標和健康檢查等生產就緒功能中受益,即所謂的“可觀察性” . (我們可以在文章“Observability with Spring Boot 3”中找到詳細信息。)
可觀察性特性由Spring Boot Actuator提供,它是 Spring Boot 的一個子項目。在本文中,我們將了解如何將 Actuator 集成到不使用 Spring Boot 的應用程序中。
2.項目配置
排除Spring Boot時,我們需要處理應用打包和服務器運行時配置,需要我們自己外化配置。 Spring Boot 提供的那些功能對於在我們基於 Spring 的應用程序中使用 Actuator 不是必需的。而且,雖然我們確實需要項目依賴項,但我們不能使用 Spring Boot 的啟動依賴項(在本例中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.啟用端點
默認情況下,僅啟用健康端點。執行器的自動配置類使用配置屬性。例如, WebEndpointAutoConfiguration
使用映射到具有“management.endpoints.web”
前綴的屬性的WebEndpointProperties
。要啟用所有端點,我們需要
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.測試項目配置
現在,我們已準備好調用執行器端點。我們可以使用此屬性啟用健康詳細信息:
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 Actuator。像往常一樣,所有代碼實現都可以在 GitHub 上找到。