首页 > 解决方案 > Swagger:为特定@Api路径下的所有请求定义通用参数

问题描述

我正在尝试重构一些代码并为特定的@Api 路径(每个控制器一次)全局定义一个常用的 HeaderParameter(现在我们称之为“myCommonParam”)。否则,我将不得不为我的控制器中的每个操作/http 请求定义 HeaderParameter。

在做了一些研究之后,我找到了一种globalOperationParameters通过 springfox 配置指定的方法(示例 1)。

示例 1:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                ...
                .globalOperationParameters(Collections.singletonList(
                new ParameterBuilder()
                        .name("myCommonParam")
                        .description("my common param.")
                        .modelRef(new ModelRef("string"))
                        .parameterType("header")
                        .required(false)
                        .build())
        );
    }
}

这种方法的实际问题是我有多个控制器(api 路径)并且只希望 HeaderParameter 申请其中一些。最好的解决方案是,如果我可以为每个类定义一次常用参数,就像预期所示。

实际的:

@Api(value = "firstController")
public class MyFirstController {

    public void apiOperation_1(@RequestHeader(name = "myCommonParam", required = false) @ApiParam(value = "my common param.", required = false) String myCommonParam){
        // not neccessary
    }

    public void apiOperation_2(@RequestHeader(name = "myCommonParam", required = false) @ApiParam(value = "my common param.", required = false) String myCommonParam){
        // not neccessary
    }
}

预期的:

@Api(value = "firstController")
>>> somehow define the 'myCommonParam' parameter here? <<<
public class MyFirstController {


    public void apiOperation_1(){
        // not neccessary
    }

    public void apiOperation_2(){
        // not neccessary
    }
}

标签: javaspring-mvcswaggerspringfox

解决方案


推荐阅读