重用复杂的 spring-fox swagger 注释

reuse complex spring-fox swagger annotation

我正在使用 spring-fox2 @ApiImplicitParam 注释使 swagger-ui 显示一个包含授权 header 请求的框:

@ApiImplicitParams({
        @ApiImplicitParam(
                name="Authorization",
                value="authorization header containing the bearer token",
                paramType = "header"
        )
})
public void someControllerMethod() {
    ...
}

这很好用,但我需要为控制器中的每个方法授权 header。复制和粘贴这是代码味道。我可以为此定义某种快捷方式注释吗?是否有不同的方式告诉 swagger-ui 为授权 header 创建输入字段?

谢谢!

解决您的问题的另一种方法是根本不使用注释。而是使用摘要 add global operation parameters 参见#22。您可以将 headers 添加到摘要中的所有操作。

这种方法的缺点可能是您最终可能会配置多个摘要,这样您 pre-select(请参阅#4、#5、#6)将这些参数添加到哪些操作中。

作为替代解决方案(我不知道上面的选项),我创建了自己的注释,像这样重用 ApiImplicitParam:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
@ApiImplicitParams({
    @ApiImplicitParam(dataType = "string", paramType = "header", name = HttpHeaders.AUTHORIZATION, value = Constants.ApiKey.DESC),
})
public @interface ApiGetMappingV2 {
    /**
     * Alias for {@link RequestMapping#name}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    /**
     * Alias for {@link RequestMapping#value}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String value() default "";
}

然后我只使用该注释而不是映射注释:

    @ApiGetMapping("/foo")
    @ApiOperation(value = "List all available foos")
    public List<Foo> all() throws MyCustomApiException {

不过,这种方法不适用于 @ApiParam,因为它使用的是目标。