如何使用简单代码列出Spring Boot暴露的所有端点? - Zanini


让我们看看如何定义一个自定义API,以返回使用Spring Boot应用程序公开的所有端点的列表。
在网上寻找在Spring Boot应用程序中检索所有已部署端点的方法时,我发现存在RequestMappingHandlerMapping
Spring Boot使用此类来执行每个带有注释的方法,@RequestMapping 并包含所有方法的列表,尤其是应用程序所有公开的端点的列表。
这就是为什么实现这样的API比您想象的要容易的原因。这可以通过以下方式实现:

@RestController
@RequestMapping("/monitoring/")
public class MonitoringController {
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @GetMapping(
"endpoints")
    public ResponseEntity<List<String>> getEndpoints() {
        return new ResponseEntity<>(
                requestMappingHandlerMapping
                        .getHandlerMethods()
                        .keySet()
                        .stream()
                        .map(RequestMappingInfo::toString)
                        .collect(Collectors.toList()),
                HttpStatus.OK
        );
    }
}

Kotlin:
@RestController
@RequestMapping("/monitoring/")
class MonitoringController {
    @Autowired
    private lateinit var requestMappingHandlerMapping : RequestMappingHandlerMapping

    @GetMapping(
"endpoints")
    fun getEndpoints() : ResponseEntity<List<String>> {
        return ResponseEntity(
            requestMappingHandlerMapping
                .handlerMethods
                .map {
                    it.key.toString()
                },
            HttpStatus.OK
        )
    }
}

在这两种情况下,我都使用handlerMethods属性,该属性存储具有所有映射和HandlerMethod的只读映射。映射是条目的键,并由RequestMappingInfo对象表示。他们的toString()方法返回到达与HandlerMethod对象关联的端点所需的全部信息。
这是此API响应示例:

   “ {GET / monitoring / endpoints}”,       
   “ {GET / v1 / genres}”,     
   “ {GET / v1 / genres / {id}}”,
   “ {POST / dex / v1 / genres}”,
   “ {PUT / v1 / genres / {id}}”,
   “ {DELETE / v1 / genres / {id}}”,      
   “ {PATCH / v1 / genres / {id}}”,
   “ {GET / v1 / books}”,     
   “ {GET / v1 / books / {id}}”,
   “ {POST / dex / v1 / books}”,
   “ {PUT / v1 / books / {id}}”,
   “ {Delete / v1 / books / {id} }”,      
   “ {PATCH / v1 / books / {id}}”,
   “ {GET / v1 / authors}”,     
   “ {GET / v1 / authors / {id}}”,
   “ {POST / dex / v1 / authors }“,
   ”{PUT / v1 / authors / {id}}”, 
   “ {DELETE / v1 / authors / {id}}”,      
   “ {PATCH / v1 / authors / {id}}”,
   “ {GET / v1 / authors / {id} / books}”     
]