1. 概述
在使用 REST API 時,通常需要檢索所有 REST 端點。例如,我們可能需要將所有請求映射端點保存到數據庫中。在本教程中,我們將探討如何在 Spring Boot 應用程序中獲取所有 REST 端點。
2. 映射端點
在 Spring Boot 應用程序中,我們通過在控制器類中使用 @RequestMapping 註解來暴露 REST API 端點。 獲取這些端點有三種方法:事件監聽器、Spring Boot Actuator 或 SpringDoc 庫。
3. Event Listener Approach
為了創建 REST API 服務,我們在控制器類中使用 @RestController 和 @RequestMapping。這些類在 spring 應用程序上下文中註冊為 spring bean。因此,我們可以使用事件監聽器在應用程序上下文準備好時獲取端點。定義監聽器有兩種方式。我們可以實現 ApplicationListener 接口,或者使用 @EventListener 註解。
3.1. ApplicationListener 接口
當實現 ApplicationListener 時,必須定義 onApplicationEvent() 方法:
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext
.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping
.getHandlerMethods();
map.forEach((key, value) -> LOGGER.info("{} {}", key, value));
}
通過這種方式,我們使用 ContextRefreshedEvent 類。此事件在 ApplicationContext 初始化或刷新時發佈。Spring Boot 提供許多 HandlerMapping 實現。其中之一是 RequestMappingHandlerMapping 類,該類檢測請求映射並由 @RequestMapping 註解使用。因此,我們在 ContextRefreshedEvent 事件中使用此 bean。
3.2. @EventListener 註解
另一種映射我們端點的方法是使用 @EventListener 註解。我們將此註解直接應用於處理 ContextRefreshedEvent 的方法:
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext
.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping
.getHandlerMethods();
map.forEach((key, value) -> LOGGER.info("{} {}", key, value));
}
4. Actuator 方式
通過 Spring Boot Actuator 特性獲取所有端點的另一種方式。
4.1. Maven 依賴
為了啓用此功能,我們將 spring-boot-starter-actuator Maven 依賴添加到我們的 pom.xml 文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
4.2. 配置
默認情況下,當我們添加 spring-boot-actuator 依賴時,只有 /health 和 /info 端點可用。為了啓用所有 Actuator 端點,我們可以通過向我們的 application.properties 文件添加屬性來啓用它們:
management.endpoints.web.exposure.include=*
或者,我們可以簡單地 暴露用於檢索 mappings 的端點:
management.endpoints.web.exposure.include=mappings
啓用後,應用程序的 REST API 端點可在 http://host/actuator/mappings 上訪問。
5. SpringDoc
SpringDoc 庫也可以用於列出 REST API 的所有端點。
5.1. Maven 依賴
要將其添加到我們的項目,我們需要在 springdoc-openapi-ui 依賴項在 pom.xml 文件中:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
5.2. 配置
讓我們通過定義 OpenAPI 豆來創建配置類:
@Bean
public OpenAPI openAPI() {
return new OpenAPI().info(new Info().title("SpringDoc 示例")
.description("SpringDoc 應用程序")
.version("v0.0.1"));
}
要訪問 REST API 端點,可以在瀏覽器中訪問以下 URL:
http://localhost:8080/swagger-ui/index.html
6. 結論
在本文中,我們描述瞭如何通過使用 Event Listener、Spring Boot Actuator 和 SpringDoc 庫來檢索 Spring Boot 應用程序中的請求映射端點。