【问题标题】:Return all available mappings on RequestMethod GET返回 RequestMethod GET 上的所有可用映射
【发布时间】:2016-03-30 23:24:20
【问题描述】:

我正在学习 Spring Boot 并拥有一个带有 JPA 的 REST 服务器。 对于我的 RestControllers,我希望在基本页面上具有这样的行为,即当有人转到基本页面时,他们将能够在基本页面下看到所有可用的 RequestMappings。

@RestController
@RequestMapping("/food")
public class FoodRestController {

@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public Iterable<Food> printAllFoods() {
    return foodRepository.findAll();
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addFood(@RequestBody Food f) {
    foodRepository.save(f);

    HttpHeaders httpHeaders = new HttpHeaders();
    return new ResponseEntity<Food>(f, httpHeaders, HttpStatus.CREATED);
}

因此,对于上述内容,转到“localhost:8080/food”会给出一个显示类似无效端点的页面,可能的端点是 localhost:8080/food/all 或 localhost:8080/food/add。 我可以只使用带有 GET 的 RequestMapping 并将其作为正文返回,但这将是手动键入的响应。想看看Spring是否提供类似的东西

【问题讨论】:

    标签: spring rest spring-mvc spring-boot


    【解决方案1】:

    您也可以使用 Swagger 。它实际上是一个文档框架。它还围绕漂亮的 UI 构建,以试用随文档提供的 API。

    【讨论】:

      【解决方案2】:

      SpringBoot Actuator 已经具有执行此类操作的功能。添加对SpringBoot Actuator 的依赖,启动应用程序并将浏览器指向:

      http://[yourHostAndPort]/mappings

      这将产生类似于以下内容(假设为 JSON),其中包含作为项目一部分的 ALL 映射(Spring 端点也是如此!)。

      {
        ...
          "{[/refresh],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}": {
              "bean": "endpointHandlerMapping",
              "method": "public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()"
          },
          "{[/restart],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}": {
              "bean": "endpointHandlerMapping",
              "method": "public java.lang.Object org.springframework.cloud.context.restart.RestartMvcEndpoint.invoke()"
          },
          "{[/configprops],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}": {
              "bean": "endpointHandlerMapping",
              "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"
          },
          "{[/env],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}": {
              "bean": "endpointHandlerMapping",
              "method": "public java.lang.Object org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.value(java.util.Map<java.lang.String, java.lang.String>)"
          },
        ...
      }
      

      这个 sn-p 显示了一小部分可从其他一些 Actuator 端点获得的映射。

      我了解您的要求有些不同,因此如果此设置不是您所需要的,您应该能够创建自己的端点来执行类似的操作,只需浏览SpringBoot Actuator source code。为 mappings 端点完成大部分工作的特定文件是 org.springframework.boot.actuate.endpoint.RequestMappingEndpoint.java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 2021-08-11
        • 2019-10-12
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多