首页 文章

使用Springfox-Swagger2在Swagger UI中自定义请求标头描述

提问于
浏览
3

我在Spring Boot应用程序中使用Springfox Swagger2版本2.4.0,Springfox Swagger UI版本2.4.0和Swagger Annotations版本1.5.0 .

这里的问题是,我能够为我的控制器的API生成swagger UI,我能够测试相同的 . 但我无法为我的请求标头指定请求标头描述 . 我使用@RequestHeader注释 .

我的控制器API中的代码段如下:

@RequestHeader(name = "Api-Key") String apiKey

请求标头的Swagger UI如下:

enter image description here

图像中突出显示的矩形区域表示请求 Headers 的描述 .

目前它只是获取name属性中提到的数据并显示它 . 但是我想给出不同的描述 . 即“许可证密钥的 Value ”

我如何在Swagger UI中实现这一点,因为@RequestHeader注释只有value,defaultValue,name和required属性?任何帮助将非常感激 .

更新:寻找一个开箱即用的解决方案,没有任何我自己的自定义注释

2 回答

  • 3

    也许我的回答会对某人有所帮助 .

    正如在his answer中提到的Dilip Krishnan,您可以使用 io.swagger.annotations.ApiParamio.swagger.annotations.ApiImplicitParam Swagger注释来进行微调自定义文档 .

    @ApiParam 可用于已注册的方法参数 .

    如果未明确注册API参数,则可以使用 @ApiImplicitParam .

    @RestController
    @RequestMapping(value = "/v1/test", produces = "application/json")
    @Api(value = "/v1/test")
    public class TestController {
    
        @ApiOperation(value = "Do Something method", tags = "Test method")
        @RequestMapping(value = "/doSomeThing", method = RequestMethod.GET)
        public Foo doSomeThing(
                @ApiParam(value = "Param1 Description", required = true)
                @RequestParam String param) {
            throw new UnsupportedOperationException("do Some Things");
        }
    
        @ApiOperation(value = "Do Something Another method", tags = "Test method")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "anotherParam1", value = "Another Param1 Description", paramType = "header"),
                @ApiImplicitParam(name = "anotherParam1", value = "Another Param1 Description", paramType = "header")
        })
        @RequestMapping(value = "/doSomeThingAnother", method = RequestMethod.GET)
        public Foo doSomeThingAnother(Bar bar) {
            throw new UnsupportedOperationException("do Some Thing Another");
        }
    
    
    }
    

    最后你可以看到下面的图片

    Swagger UI for custom method description

  • 6

    TL; DR是你必须 Build 自己的插件才能做到这一点 .

    基本上,在这种情况下唯一可以增加描述的开箱即用注释是 @ApiParam 并且更准确 @ApiImplicitParam . 不幸的是,这些注释都不支持描述 .

    所以我的建议是:

    • 创建自己的注释,如下所示

    @RequestHeader(name = "Api-Key") @Description("Value of license key") String apiKey

    注意:已经有annotation in spring适合这个 .

    public class Test implements ParameterBuilderPlugin {
      @Override
      public void apply(ParameterContext parameterContext) {
        ResolvedMethodParameter methodParameter =parameterContext.resolvedMethodParameter();
        Optional<Description> requestParam = methodParameter.findAnnotation(Description.class);
        if (requestParam.isPresent()) {
          parameterContext.parameterBuilder()
            .description(requestParam.get().value());
        }
      }
    
      @Override
      public boolean supports(DocumentationType documentationType) {
        return false;
      }
    }
    

    另请将springfox库升级到latest version .

相关问题